Why can't class variables be used in __init__ keyword arg?

I cannot find documentation about when exactly the class can refer to itself. In the future, he will fail. This is because the class was created but not initialized to the next line __init__, right?

class A(object):
    class_var = 'Hi'
    def __init__(self, var=A.class_var):
        self.var = var

So, in the case where I want to do this, this is the best solution:

class A(object):
    class_var = 'Hi'
    def __init__(self, var=None)
        if var is None:
            var = A.class_var
        self.var = var

Any help or documentation appreciated!

+4
source share
1 answer

Python scripts are interpreted the way you go. Therefore, when the interpreter enters __init__(), the class variable Ahas not yet been defined (you are inside it), the same with self(this is a different parameter and is available only in the body of the function).

, class_var , .

class A(object):
    class_var = 'Hi'
    def __init__(self, var=class_var):
        self.var = var

, ...

+6

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


All Articles