Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use class name in class scope?

Tags:

python

class

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?

like image 614
Goat Avatar asked Oct 27 '13 19:10

Goat


1 Answers

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.)

like image 85
BrenBarn Avatar answered Oct 03 '22 11:10

BrenBarn