[BangPypers] wierd class behavior

Anand Chitipothu anandology at gmail.com
Tue Dec 4 04:54:25 CET 2012


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/


More information about the BangPypers mailing list