Brian
Brian

Reputation: 1025

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!

Upvotes: 4

Views: 543

Answers (1)

Nils Werner
Nils Werner

Reputation: 36839

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

Upvotes: 6

Related Questions