Nested Class vs. Scope

Viewed 63

I'm new to programming. First, the following is my code:

x = 11

def f():
    x = 22
    print(x)
    class C:
        print(x)

f()

I got three printed results, "22 22", as output. When I changed my code like this:

x = 11

def f():
    x = 22
    print(x)
    class C:
        print(x)
        x = 33
        print(x)

f()

I got "22 11 33" instead of what I'm expecting: "22 22 33".

It seems like when I add a local x in the nested class, the order of variable searching is changed. I believe there's some tricks about scopes that I don't know yet. Can anyone explain this to me?

0 Answers
Related