[BangPypers] wierd class behavior

Satyajit Ranjeev satyajit.ranjeev at gmail.com
Tue Dec 4 05:08:51 CET 2012


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.

The other cases can be expanded on the same basis.

You can understand more about Python objects in the execution model documentation(http://docs.python.org/3/reference/executionmodel.html).

Another good read would be http://www.jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/.

Cheers!

Satyajit 

http://satyajit.ranjeev.in



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

> Python scoping rules when it comes to classes are so confusing.
> 
> Can you guess what would be output of the following program?
> 
> x = 1
> 
> class Foo:
>    print(x)
>    x = x + 1
>    print(x)
> 
> print(x, Foo.x)
> 
> Now take the same piece of code and put it in a function.
> 
> def f():
>    x = 1
> 
>    class Foo:
>        print(x)
>        x = x + 1
>        print(x)
> 
>    print(x)
>    print(Foo.x)
> 
> f()
> 
> To add more to your confusion, try this too:
> 
> def g():
>    y = 1
>    class Foo:
>        y = 2
>        def gety(self):
>            return y
> 
>    foo = Foo()
>    print(y, foo.y, foo.gety())
> 
> g()
> 
> Does it make any sense?
> 
> --
> Anand
> http://anandology.com/
> _______________________________________________
> BangPypers mailing list
> BangPypers at python.org
> http://mail.python.org/mailman/listinfo/bangpypers



More information about the BangPypers mailing list