Variables visibility for methods

juraseg yuri.abzyanov at gmail.com
Wed Aug 31 23:07:02 EDT 2016


среда, 31 августа 2016 г., 14:09:16 UTC+7 пользователь ast написал:
> Hello
> 
> I made few experiments about variables visibility
> for methods.
> 
> class MyClass:
>     a = 1
>     def test(self):
>         print(a)
> 
> obj = MyClass()
> obj.test()
> 
> Traceback (most recent call last):
>   File "<pyshell#16>", line 1, in <module>
>     obj.test()
>   File "<pyshell#7>", line 4, in test
>     print(a)
> NameError: name 'a' is not defined
> 
> =========== RESTART: Shell ==============
> 
> a = 1
> 
> class MyClass:
>     def test(self):
>         print(a)
> 
> obj = MyClass()
> obj.test()
> 1
> 
> So it seems that when an object's méthod is executed, variables
> in the scope outside the object's class can be read (2nd example),
> but not variables inside the class (1st example).
> 
> For 1st example, I know that print(MyClass.a) or print(self.a)
> would have work.
> 
> Any comments are welcome.

Class construction in Python does not have scope in usual way. In fact "class" construct is essentially a syntactic sugar to call of "type" built-in function (https://docs.python.org/3.5/library/functions.html#type) and then adding all the parts manually. 

When you put a variable inside class definition but outside of any method body the variable becomes class attribute (so can be accessed by using MyClass.var or self.var if inside method body, keep in mind though that assigning to self.var creates instance attribute instead of changing class attribute)



More information about the Python-list mailing list