Dynamically get class name in class level variable in python

The question is simple, and I tried to make the indentation suitable for readability. I'm just starting out with Python, and here is what I have now:

class BaseKlass(): .... class DerivedKlass1(BaseKlass): display_name = "DerivedKlass1" class DerivedKlass2(BaseKlass): display_name = "DerivedKlass2" 

So basically all derived classes have

display_name named hardcoded.

What I want is to have the instance_name set to BaseKlass and remove the display_name declaration from the child classes as follows:

 class BaseKlass(): display_name = <some way to set the display name to callee class name> class DerivedKlass1(BaseKlass): .... class DerivedKlass2(BaseKlass): .... 

So DerivedKlass1.display_name should return "DerivedKlass1", and DerivedKlass2.display_name should return "DerivedKlass2".

I know that I am missing something very obvious, and I expect a lot of RTFM comments, but whatever I want is to learn how to dynamically set the python class name for the level attribute. Therefore, do not hesitate to vote if you want, but I will be grateful if you leave an answer.

Thanks,

+6
source share
1 answer

You can access the class name of an object using

 obj.__class__.__name__ 

You will need to do this as soon as the instance is created. The most direct way would be

 class MyClass: def __init__(self): self.display_name = self.__class__.__name__ 

You may also be able to use the metaclass so that it automatically installs, but I don’t think it would be useful, and I can’t remember how they work right now.

+5
source

Source: https://habr.com/ru/post/949494/


All Articles