5

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?

4
  • 1
    @Barmar From my reading it doesn't look like this case is covered in that question. Commented Nov 23, 2017 at 1:34
  • @thebjorn I'm having trouble finding anything about classes nested in functions. When I google for info about nested classes, it's all about classes nested in other classes. Commented Nov 23, 2017 at 1:37
  • this question may be more helpful Commented Nov 23, 2017 at 1:38
  • @Barmar if you go to the last answer and end up at stackoverflow.com/questions/20246523/… you should be set :-) Commented Nov 23, 2017 at 1:48

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.