3
x = "xtop"
y = "ytop"
def func():
    x = "xlocal"
    y = "ylocal"
    class C:
        print x  #xlocal  of course
        print y  #ytop  why? I guess output may be 'ylocal' or '1'
        y = 1
        print y  #1  of course
func()
  1. Why x and y are different here?

  2. If I replace class C with a function scope I will get UnboundLocalError: local variable 'y' referenced before assignment,What is the difference between a class and a function in this situation?

0

1 Answer 1

3

The reason for this is because the scope of class C is actually different than the scope of def func - and the different defaulting behaviors of scopes that python has for resolving names.

Here is basically how python looks for a variable in a step-by-step guide:

  • Look in current scope
  • If current scope doesn't have it → use nearest enclosing scope
  • If current scope has it, but not yet defined → use global scope
  • If current scope has it, and already defined → use it
  • Otherwise we blow up

(If you remove ytop you get the exception NameError: name 'y' is not defined)

So basically, when the interpreter looks at the following section of code it does this

class C:
    print(x) # need x, current scope no  x → default to nearest (xlocal)
    print(y) # need y, current scope yes y → default to global  (ytop)
             #         but not yet defined 
    y = 1
    print(y) # okay we have local now, switch from global to local scope

Consider the following scenarios and the different outputs we would get in each case

1) class C:
    print(x)
    print(y)

>>> xlocal
>>> ylocal

2) class C:
    y = 1
    print(x)
    print(y)  

>>> xlocal
>>> 1

3) class C:
    print(x)
    print(y)
    x = 1
 
>>> xtop
>>> ylocal
Sign up to request clarification or add additional context in comments.

6 Comments

Why will we get an output, no object of class C is created?
@ShashankSingh In python, all class objects are evaluated immediately. def objects (functions) are not.
If I replace class C with def C(): function and call it after its definition I get UnboundLocalError: local variable 'y' referenced before assignment,What is the difference between a class and a function in this situation?
@ShashankSingh That is a rather complex question. It has to do with how python interprets the code. You will need to read docs.python.org/3/tutorial/classes.html
The point you wrote under Here is basically how python looks for a variable applies to classes only and not function, right?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.