On Wednesday, August 31, 2016 at 12:09:16 AM UTC-7, ast wrote:
> 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.

In your example a is an attribute of MyClass, not instances of MyClass like 
obj. Refrencing a as MyClass.a returns 1. See below:

>>> class MyClass:
...     a = 1
...     def test(self):
...         print(MyClass.a)
...
>>> obj = MyClass()
>>> obj.test()
1

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to