python class attribute cannot used as an argument for constructor?

◇◆丶佛笑我妖孽 提交于 2019-12-11 17:48:46

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/32762134/python-class-attribute-cannot-used-as-an-argument-for-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!