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?

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
clsc999
  • 51
  • 2
  • 1
    @Barmar From my reading it doesn't look like this case is covered in that question. – thebjorn Nov 23 '17 at 01: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. – Barmar Nov 23 '17 at 01:37
  • [this question](https://stackoverflow.com/questions/4296677/creating-a-class-within-a-function-and-access-a-function-defined-in-the-containi) may be more helpful – Barmar Nov 23 '17 at 01:38
  • @Barmar if you go to the last answer and end up at https://stackoverflow.com/questions/20246523/how-references-to-variables-are-resolved-in-python you should be set :-) – thebjorn Nov 23 '17 at 01:48

0 Answers0