python class attribute cannot used as an argument

2019-08-14 03:23发布

In python 3 I found that class attribute can be used as a argument in __init__() function, like below:

file test.py:

class Foo:
    var1 = 23333
    def __init__(self, var=var1):
        self.var = var

run in cmd:

C:\Users\rikka\Desktop>py -3 -i test.py
>>> f1=Foo()
>>> f1.var
23333

but by using a dot.expression, when init this class, interpreter will report an error:

file test2.py:

class Foo:
    var1 = 23333
    def __init__(self, var=Foo.var1):
       self.var = var

run in cmd:

C:\Users\rikka\Desktop>py -3 -i test2.py
Traceback (most recent call last):
  File "test2.py", line 1, in <module>
    class Foo:
  File "test2.py", line 3, in Foo
    def __init__(self, var=Foo.var1):
NameError: name 'Foo' is not defined

I just don't know why interpreter cannot find name 'Foo' since Foo is a name in the global frame in the environment. is there something scope related concept about python class that I don't fully understand?

2条回答
劳资没心,怎么记你
2楼-- · 2019-08-14 03:37

Function defaults are set at function definition time, not when being called. As such, it is not the expression var1 that is stored but the value that variable represents, 23333. var1 happens to be a local variable when the function is defined, because all names in a class body are treated as locals in a function when the class is built, but the name Foo does not yet exist because the class hasn't finished building yet.

Use a sentinel instead, and in the body of the function then determine the current value of Foo.var1:

def __init__(self, var=None):
    if var is None:
        var = Foo.var1
    self.var = var

I used None as the sentinel here because it is readily available and not often needed as an actual value. If you do need to be able to set var as a distinct (i.e. non-default) value, use a different singleton sentinel:

_sentinel = object()

class Foo:
    var = 23333

    def __init__(self, var=_sentinel):
        if var is _sentinel:
            var = Foo.var1
        self.var = var
查看更多
来,给爷笑一个
3楼-- · 2019-08-14 03:46

The problem is that you are trying to reference Foo during its very construction. At the moment that Foo.__init__ is defined, which is when Foo.var is evaluated, Foo does not exist yet (as it's methods, i.e. Foo.__init__ itself, have not been fully constructed yet).

Function/method default parameters are resolved during function/method definition. Classes are only available after definition. If a class method definition (i.e. parameters) references the class itself, you get a circular dependency. The method cannot be defined without the class, and the class cannot be defined without its method.

See Martijn Pieters reply on how to actually approach such dependencies.

查看更多
登录 后发表回答