[BangPypers] wierd class behavior
Satyajit Ranjeev
satyajit.ranjeev at gmail.com
Tue Dec 4 05:43:08 CET 2012
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()
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.
On 04-Dec-2012, at 9:42 AM, Anand Chitipothu <anandology at gmail.com> wrote:
> On Tue, Dec 4, 2012 at 9:38 AM, Satyajit Ranjeev
> <satyajit.ranjeev at gmail.com> wrote:
>> It is the way Python handles objects. Unlike variables in C/C++ where a variable can point to an address location in the memory Python uses variables to point to an object.
>>
>> Now in the first case what you are doing is pointing x to the object 1 in x=1.
>> When you print x it just prints 1. When you try to assign x to x+1 you are pointing x in the class's scope to a new object which is x + 1 or 2. And that's why you get the weird results.
>
> Well, *the class scope* is quite different from function scope.
>
> The same code that works in a class, fails in a function.
>
> x = 1
>
> class Foo:
> x = x + 1
>
> def f():
> x = x + 1
>
>>
>> The other cases can be expanded on the same basis.
>
> Did you try the other ones?
>
> Anand
> _______________________________________________
> BangPypers mailing list
> BangPypers at python.org
> http://mail.python.org/mailman/listinfo/bangpypers
More information about the BangPypers
mailing list