[BangPypers] wierd class behavior

steve steve at lonetwin.net
Tue Dec 4 11:56:19 CET 2012


On Tuesday 04 December 2012 09:24 AM, Anand Chitipothu 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)

Prints the global x

>      x = x + 1
>      print(x)
Prints the local x, with the reference to the global x lost in the classes scope.

>
> print(x, Foo.x)

prints (1, 2) -- ie: the 'global x' and the class local x. So, does the right 
thing. What were you expecting ?

>
> 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()
>

Again, global versus local difference for the /class/. Still not sure what you 
were expecting,

> 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()
>
Ok, this is slightly confusing but still consistent. You'd understand the source 
of your confusion if you changed the definition for gety() to:
...
...
         def gety(self):
             return self.y
...
...


> Does it make any sense?
Well, it does if you know the rules.

http://effbot.org/pyfaq/what-are-the-rules-for-local-and-global-variables-in-python.htm

Try this:

x = 1
class Foo:
     print(x)  # this is the global x
     x = x + 1 # this is the local x
     print(x)
     global x  # now lets be explicit
print(x, Foo.x)

what happened here ?

cheers,
- steve



More information about the BangPypers mailing list