Skip to content Skip to sidebar Skip to footer

Python Class Attribute Cannot Used As An Argument For Constructor?

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

Solution 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):
    ifvar 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()

classFoo:
    var = 23333

    def __init__(self, var=_sentinel):
        ifvaris _sentinel:
            var = Foo.var1
        self.var = var

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

Post a Comment for "Python Class Attribute Cannot Used As An Argument For Constructor?"