Python variable scope and classes

In Python, if I define a variable:

my_var = (1,2,3) 

and try to access it in the class __init__ function:

 class MyClass: def __init__(self): print my_var 

I can access it and print my_var without specifying (global my_var).

If I put my_var right after the class MyClass , I get a scope error (no global variable found) .

What is the reason for this? How can I do it? Where can I read about this to find out? I read the Python class page, but I did not find an explanation.

thanks

+4
source share
4 answers

When you put it right after class MyClass , it becomes an attribute of the class, and you can access it through MyClass.my_var or as self.my_var from the class (provided that you do not create an instance variable using the same name).

Here is a small demo:

 my_var = 'global' class MyClass(object): my_var = 'class' def __init__(self): print my_var #global print MyClass.my_var #class print self.my_var #class -- Only since we haven't set this attribute on the instance self.my_var = 'instance' #set instance attribute. print self.my_var #instance print MyClass.my_var #class 
+9
source

In addition to @mgilson's answer: Note that Python class variables are shared between class instances. And the behavior can be VERY unexpected and seem strange. In practice, it works as follows:

 class MyClass(object): my_var = 10 def __init__(self): print(self.my_var) m1 = MyClass() print(m1.my_var) >>> 10 # this is fine MyClass.my_var = 20 print(m1.my_var) >>> 20 # WTF? :) --> shared value m2 = MyClass() print(m2.my_var) >>> 20 # this is expected m1.my_var = 30 print(MyClass.my_var) >>> 20 # this is also expected MyClass.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 value is still shared :) 
+11
source

If you write:

 class MyClass(object): my_var = (1, 2, 3) 

you are defining a MyClass attribute, not a variable. In your method __init__ , then this is MyClass.my_var .

+2
source

After the definition inside the class it is no longer global; now it is in the namespace of the class objects. You can access it with self.my_var inside __init__ , though ...

+1
source

Source: https://habr.com/ru/post/1440376/


All Articles