I am trying to understand class variables and how to change them, and I cannot understand why in this sample code, b is not changed to 9999. I am trying to permanently change b so that any time Whatever.b is called, from anywhere else in the code, it will print 9999.
class Whatever():
b = 5
def __init__(self):
Whatever.b = 9999
class test():
print(Whatever.b)
Whatever()
test()
This outputs:
5
CodePudding user response:
The test() call is irrelevant.
The print is executed during the definition of the test class. That is before Whatever is instantiated, so it is before the class attribute is set to 9999.
class Whatever():
b = 5
def __init__(self):
Whatever.b = 9999
class test():
print(Whatever.b)
# Now the print happens (while Whatever.b is still 5)
Whatever()
# Now Whatever.b is 9999
test()
If you check the value of Whatever.b any point after you have instantiated Whatever(), you will find that the value has indeed been changed to 9999.
CodePudding user response:
On the test() class you need to instantiate Whatever() like this:
myWhatever = Whatever()
print(myWhatever.b)
Then only run Test()
CodePudding user response:
The problem is that the line test() isn't the line that make the 5 print out. I can run:
class Whatever():
b = 5
def __init__(self):
Whatever.b = 9999
class test():
print(Whatever.b)
Whatever()
and it will still output 5, since the print statement is run during the definition of the class test.
Basically what your class test does is print Whatever.b without initializing class Whatever so Whatever.b never gets set to 9999.
To get 9999 outputted you want to initialise Whatever first in the class definition, like this:
class Whatever():
b = 5
def __init__(self):
Whatever.b = 9999
class test():
Whatever()
print(Whatever.b)
Whatever()
