Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python static inheritance in class variable

Tags:

python

oop

static

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

like image 470
M1L0U Avatar asked Feb 26 '26 17:02

M1L0U


1 Answers

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

like image 163
Martijn Pieters Avatar answered Mar 01 '26 06:03

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!