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.
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to