I'm not very familiar with Python. So I have some problem while I code.
It's very normal to use the function name in the function block, for example:
def factorial(n):
if n == 1:
return n
else:
return n * factorial(n-1)
But when I try to do use the class name in the class block, things go wrong:
class Foo(object):
a = Foo
NameError: name 'Foo' is not defined
Although the code below is okay:
class Foo(object):
def __init__(self):
a = Foo
Then I debug these two codes using print globals()
statement. I found that the global variable dict in class block doesn't contain class Foo
while the global variable dict in __init__
function block contains it.
So it seems that the class name binding is after the execution of class block and before the execution of function block.
But I don't like guesswork in foundation area of coding. Could anyone offer a better explanation or official material about this?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…