[BangPypers] wierd class behavior

Satyajit Ranjeev satyajit.ranjeev at gmail.com
Tue Dec 4 06:25:03 CET 2012


On 04-Dec-2012, at 10:23 AM, Anand Chitipothu <anandology at gmail.com> wrote:

> On Tue, Dec 4, 2012 at 10:13 AM, Satyajit Ranjeev
> <satyajit.ranjeev at gmail.com> wrote:
>> You are right in mentioning scopes.
>> 
>> Lets take case 2:
>> 
>> def f():
>>   x = 1                # x is pointing to object 1
>> 
>>   class Foo:
>>       print(x)         # what you are doing is printing object 1
>>       x = x + 1        # you are defining x in the class's scope and pointing it to the object 2
>>       print(x)         # printing out the x in the class's scope
>> 
>>   print(x)             # gives 1 as that's the object x is pointing in f()'s scope
>>   print(Foo.x)         # gives 2 - the object x is pointing in Foo's scope
>> 
>> f()
> 
> No, this fails with an error.
> 
> NameError: name 'x' is not defined
> 
> It tries to find x in the global scope, not in the enclosed scope.
> 
> If this is working for you, then you must have a global variable x
> defined. Try removing it.

You are right i did have a global x defined.

> 
>> Take case 3:
>> def g():
>>   y = 1
>>   class Foo:
>>       y = 2
>>       def gety(self):
>>           return y
>>   foo = Foo()
>>   print(y, foo.y, foo.gety())
>>   # when you print y it prints the y in g()'s scope.
>>   # when you print foo.y, you print y defined in Foo's scope.
>>   # foo.gety() does not return Foo.y rather the y defined earlier in the
>>   # method.
>>   # If you print locals() in gety() you will get something similar to :
>>   # {'y': 1, 'self': <__main__.Foo instance at 0x10c8041b8>, 'Foo': <class __main__.Foo at 0x10c822bb0>}
>>   # so what happens is that you are still accessing y of the functions scope.
>>   # If you had returned self.y or a Foo.y it would have been different.
>> 
>> g()
>> 
>> I don't think the first two cases are weird. But yes, case 3 does seem a bit weird especially while returning y in the method call.
> 
> What is really weird is that the class body is evaluated without
> considering the enclosed scope, but the methods defined in the class
> have access to the enclosed scope.
> 


I'm not sure if we should call it a weird behaviour, but I do agree its not very intuitive. Accessing the class' attributes must be done with a prefix, either self or the name of the class itself. 

> Anand
> _______________________________________________
> BangPypers mailing list
> BangPypers at python.org
> http://mail.python.org/mailman/listinfo/bangpypers



More information about the BangPypers mailing list