简体   繁体   中英

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

I can't find any documentation on when exactly a class can reference itself. In the following it will fail. This is because the class has been created but not initialized until after __init__ 's first line, correct?

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

So in the use case where I want to do that is this 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!

Python scripts are interpreted as you go. So when the interpreter enters __init__() the class variable A isn't defined yet (you are inside it), same with self (that is a different parameter and only available in function body).

However anything in that class is interpreted top to bottom, so class_var is defined so you can simply use that one.

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

but I am not super certain that this will be stable across different interpreters...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM