Reputation: 2683
I'm trying to learn Python and I'm stuck with shared variables between classes.
I have a class that sets a variable like this:
class CheckStuff(threading.Thread):
def __init__(self, debug):
threading.Thread.__init__(self)
self.debug = debug
self.newGames = False
def get_new_games(self):
return self.newGames
def set_new_games(self, new_games):
self.newGames = new_games
def run(self):
# DO STUFF #
# ... #
self.set_new_games(True)
return
I would like to access new_games
from my main, I tried like this:
if __name__ == "__main__":
debug = True
t1 = cs.CheckStuff(debug)
t1.start()
t1.join()
print(cs.CheckStuff(debug).get_new_games())
exit()
But this returns always False
. Where am I wrong? Any hints appreciated
Upvotes: 0
Views: 103
Reputation: 2111
In the following line
print(cs.CheckStuff(debug).get_new_games())
you make a new instance of CheckStuff class, and in the constructor you set self.newGames = False
. Then, by calling get_new_game()
method you ask the object to return its newGame
attribute, which is obviously False
.
Upvotes: 2
Reputation: 599788
You're creating a new instance of CheckStuff, which hasn't done anything so its newGames attribute is False. The instance that did run is t1
, you should use that:
print(t1.get_new_games())
(Note, there doesn't really seem to be a good reason to use threads here, but never mind.)
Upvotes: 4