In Python, if I define a variable:
my_var = (1,2,3)
and try to access it in __init__
function of a class:
class MyClass:def __init__(self):print my_var
I can access it and print my_var
without stating (global my_var).
If I put my_var
right after class MyClass
however, I get scope error (no global variable found)
.
What is the reason for this? How should I do this? Where can I read about this to learn? I did read Python Class page but I did not encounter its explanation.
Thank you
Complementing @mgilson's answer:
Note that Python Class variables are shared among the class instances. And the behaviour might be VERY unexpected and seem weird. In practice it works like this:
class MyClass(object):my_var = 10def __init__(self):print(self.my_var)m1 = MyClass()
print(m1.my_var)
>>> 10 # this is fineMyClass.my_var = 20
print(m1.my_var)
>>> 20 # WTF? :) --> shared valuem2 = MyClass()
print(m2.my_var)
>>> 20 # this is expectedm1.my_var = 30
print(MyClass.my_var)
>>> 20 # this is also expectedMyClass.my_var = 40
print(m1.my_var)
>>> 30 # But WHY? Isn't it shared? --> # The value WAS shared until m1.my_var = 30 has happened.print(m2.my_var)
>>> 40 # yep m2.my_var's value is still shared :)