where are the "class variables"?

D

Dominik Kaspar

maybe my question was badly formulated. i give it a new try:
why does the following program give the output "0 0" and not "1 0"?
why does it loop forever? and how could that problem be fixed?

import threading

class Server(threading.Thread):
running = 0

def run(self):
running = 1
while running:
print "do something here..."

def stop(self):
running = 0

server = Server()
server.start()
print server.running # should print "1"
server.stop()
print server.running # should print "0"
 
J

John Roth

Dominik Kaspar said:
maybe my question was badly formulated. i give it a new try:
why does the following program give the output "0 0" and not "1 0"?
why does it loop forever? and how could that problem be fixed?

Because your use of 'running' in the two methods are both
***local*** variables. They are neither instance nor
class variables.

to make them instance variables, they need to be
self.running.

To make them class variables, they need to be
Server.running.

Does this help?

John Roth
 
J

Jeff Epler

maybe my question was badly formulated. i give it a new try:
why does the following program give the output "0 0" and not "1 0"?
why does it loop forever? and how could that problem be fixed?

Because inside functions, an assignment to a simple name, like
running = 1
refers to a local variable, unless there is a "global" statement in
which case it refers to a module-level variable:
global running
running = 1
(this is still not what you want)
You want to refer to Server.running, as suggested in another message:
def run(self):
Server.running = 1

jeff
PS The first server.running might print 0 if the first line of
Server.run hasn't executed the first statement yet, of course, but
that's another story
 
E

Emile van Sebille

Dominik Kaspar said:
maybe my question was badly formulated. i give it a new try:
why does the following program give the output "0 0" and not "1 0"?
why does it loop forever? and how could that problem be fixed?

As written, you have a local varaible running in method run that gets set
and never changes. The class variable you're looking for is Server.running,
like this:

import time, threading

class Server(threading.Thread):
running = 0

def run(self):
Server.running = 1
while Server.running:
print "do something here..."
time.sleep(5)

def stop(self):
Server.running = 0

server = Server()
server.start()
print server.running # should print "1"
server.stop()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top