Dry
Dry

Reputation: 13

How can I get the name of a child class?

class Foo():

class Bar(Foo):

A method of Foo have to know the name of the child class. How can I get the name?

In this example I want to get "Bar".

I'm sorry for my english.

Upvotes: 1

Views: 1657

Answers (2)

Renato Byrro
Renato Byrro

Reputation: 3784

Extremely old, but since i stumbled upon this by duckduck'ing the topic...

Consider you have:

class Foo():
   pass

class Bar(Foo):
   pass

Python 3

my_bar = Bar()
type(my_bar).__name__
# Bar

Python 2

my_bar = Bar()
my_bar.__class__.__name__
# Bar

Upvotes: 0

agf
agf

Reputation: 176780

If it needs to be an instancemethod:

def meth(self): print self.__class__

If you want a classmethod:

@classmethod
def meth(cls): print cls

Upvotes: 6

Related Questions