Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically get class name at class level variable in python

The question is straightforward and I have tried to make the indentation proper for readability. I am just starting of 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 has

display_name variable with class name hardcoded.

What I want is to have display_name set in the 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 that DerivedKlass1.display_name should return "DerivedKlass1" and DerivedKlass2.display_name should return "DerivedKlass2".

I know I am missing something very obvious and I am expecting a lot of RTFM comments but regardless all I want is to learn how to dynamically set python class name to a class level attribute. So feel free to down vote the post if you would like to but I will be thankful if you leave an answer as well.

Thanks,

like image 961
splintercell Avatar asked Jul 15 '13 19:07

splintercell


1 Answers

You can access an object's class name with

obj.__class__.__name__

You'll need to do so once the instance has been created tho. Most straight forward way would be

class MyClass:

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

You could also probably use a metaclass to have it set automatically, but I don't think it'd be worth the trouble, plus i can't remember how those work exactly right now.

like image 132
astrognocci Avatar answered Nov 09 '22 07:11

astrognocci