Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get subclass name?

Tags:

Is it possible to get the name of a subclass? For example:

class Foo:     def bar(self):         print type(self)  class SubFoo(Foo):     pass  SubFoo().bar() 

will print: < type 'instance' >

I'm looking for a way to get "SubFoo".

I know you can do isinstance, but I don't know the name of the class a priori, so that doesn't work for me.

like image 551
Bryan Ward Avatar asked Jul 23 '10 00:07

Bryan Ward


People also ask

How do you find the class name for a subclass?

The Class object has a getName() method that returns the name of the class. So your displayClass() method can call getClass(), and then getName() on the Class object, to get the name of the class of the object it finds itself in.

What is the name of the subclass?

Answer. superclass is also known as base class and subclass is also known as derived class.

How do you get a subclass in Python?

Python 3.6 - __init_subclass__ As other answer mentioned you can check the __subclasses__ attribute to get the list of subclasses, since python 3.6 you can modify this attribute creation by overriding the __init_subclass__ method.

What is __ subclasses __ in Python?

A class that is derived from another class is known as a subclass. This is a concept of inheritance in Python. The subclass derives or inherits the properties of another class.


2 Answers

you can use

SubFoo().__class__.__name__ 

which might be off-topic, since it gives you a class name :)

like image 78
mykhal Avatar answered Sep 27 '22 19:09

mykhal


#!/usr/bin/python class Foo(object):   def bar(self):     print type(self)  class SubFoo(Foo):   pass  SubFoo().bar() 

Subclassing from object gives you new-style classes (which are not so new any more - python 2.2!) Anytime you want to work with the self attribute a lot you will get a lot more for your buck if you subclass from object. Python's docs ... new style classes. Historically Python left the old-style way Foo() for backward compatibility. But, this was a long time ago. There is not much reason anymore not to subclass from object.

like image 42
nate c Avatar answered Sep 27 '22 20:09

nate c