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.
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.
Answer. superclass is also known as base class and subclass is also known as derived class.
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.
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.
you can use
SubFoo().__class__.__name__
which might be off-topic, since it gives you a class name :)
#!/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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With