3

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

0

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.