Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

python - How to use class name in class scope?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your explanation is correct:

the class name binding is after the execution of class block and before the execution of function block.

This is just saying that a class block is executed right away, while a function block is not executed until the function is called. Note that in both cases the name is not bound until after the object (class or function) is created; it's just that function bodies are executed after the function is created, while class bodies are executed before the class is created (as part of the class creation process).

This is because classes and functions are different beasts: when you define a class, you are defining "right now" what the class should contain (i.e., its methods and attributes); when you define a function, you are defining what is to happen at some later point (when you call it).

The documentation makes it clear:

A class definition is an executable statement. It first evaluates the inheritance list, if present. [...] The class’s suite is then executed [...]

The class body is executed at the time the class statement is executed. This is different from some other languages, where a class definition is a "declaration" which is not executed in the linear order of the source file like other statements. (I trust it's obvious why the function body is not executed when the function is defined -- there wouldn't be much point in putting code in a function if it just ran right away.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...