How to use class name in class scope?

I am not very familiar with Python. So I have some problems writing code.

It is very normal to use function name function block in function block , for example:

 def f(n): if n == 1: return n else: return n * f(n-1) 

But when I try to use class name class block , everything goes wrong:

 class Foo(object): a = Foo NameError: name 'Foo' is not defined 

Although the code below is fine:

 class Foo(object): def __init__(self): a = Foo 

Then I debug these two codes using the print globals() operator. I found that the global dict variable in class block does not contain class Foo while the global dict variable in __init__ function block contains it.

Thus, it seems that class name binding occurs after class block execution and before function block execution.

But I do not like guesswork in the fundamental field of coding. Can anyone suggest a better explanation or official material on this?

+6
source share
1 answer

Your correct explanations:

binding the class name after executing the class block and before executing the function block.

It just says that the class block is executed immediately, and the function block is not executed until the function is called. Please note that in both cases the name is not bound until an 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 animals: when you define a class, you define "right now" what the class should contain (that is, its methods and attributes); when you define a function, you determine what should happen at some later point (when you call it).

The documentation makes it clear:

A class definition is an executable statement. He first evaluates the inheritance list, if present. [...] Then the class package is executed [...]

The body of the class is executed during the execution of the class statement. This differs from some other languages, where the class definition is a “declaration” that does not run in the linear order of the source file, like other operators. (I believe that it is obvious why the body of the function is not executed when the function is defined - it would not make sense to specify the code in the function if it was launched immediately.)

+5
source

Source: https://habr.com/ru/post/956831/


All Articles