M1L0U M1L0U - 3 months ago 23
Python Question

Python static inheritance in class variable

In python, is there a way to get the class name in the "static constructor"? I would like to initialize a class variable using an inherited class method.

class A():
@classmethod
def _getInit(cls):
return 'Hello ' + cls.__name__

class B(A):
staticField = B._getInit()



NameError: name 'B' is not defined

Answer

The name B is not assigned to until the full class suite has been executed and a class object has been created. For the same reason, the __name__ attribute on the class is not set until the class object is created either.

You'd have to assign that attribute afterwards:

class A():
    @classmethod
    def _getInit(cls):
        return 'Hello ' + cls.__name__

class B(A):
    pass

B.staticField = B._getInit()

The alternative is to use a class decorator (which is passed the newly-created class object) or use a metaclass (which creates the class object in the first place and is given the name to use).