Class variable initialization in python

928 views Asked by At

I have a class with a variable that should be an instance of this class. I can't create an instance at the declaration line because python interpreter does not know how to construct object at that moment. There is a possible workaround: initializing after the class declaration.

class A(object):
    static_variable = None

    def some_method(self, a=static_variable):
       print a

A.static_variable = A()

But I need to use that class variable as a default argument. It is possible to solve the problem this way:

def some_method(self, a=None):
    a = a if a else A.static_variable
    print a

However, it looks very nonpythonic to me. Any suggestion about how to use this kind of static variable as a default argument would be appreciated.

1

There are 1 answers

0
Dan On

Python does not support 'static' variables in the sense that languages like C++ do. So in this case, 'static_variable' is actually a class variable which is why you are encountering this problem. I'm sure you already know this, but others may stumble here someday and see us calling it a static variable so it seems like we should clear that up for posterity.

I was thinking that since 'static_variable' is still a member of class A, then maybe there was a way around by not using it as an argument at all.

Can you use a keyword argument in some_method()?

instead of using it as a default argument to the function, you could just call the variable 'A.static_variable' if the kwarg was not used.

class A(object):
    static_variable = None

    def some_method(self, *, a=None):
        if a:
            print(a)
        else:
            print(A.static_variable)

A.static_variable = A()