Take the following code:
import something
def Foo():
something = something.SomeClass()
return something
…this is apparently not valid code:
UnboundLocalError: local variable 'something' referenced before assignment
…as the local variable something
is created, but not assigned, before the RHS of the =
is evaluated. (See, for example, this related answer's comment.) This seems a bit odd to me, but sure, I'll go with it. Now, why is the following valid code?
class Foo(object):
something = something.SomeClass()
My understanding was that the inside of a class
definition was essentially a scope:
The class’s suite is then executed in a new execution frame (see section Naming and binding), using a newly created local namespace and the original global namespace.
So, then, why does that code act differently than that of a function?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…