I want to extract the python class name while using abstract classes with abc
library. I unfortunately instead receive the class name ABCMeta
.
import abc
class A(abc.ABC)
pass
class B(A)
pass
print(A.__class__.__name__) # output: 'ABCMeta'
print(B.__class__.__name__) # output: 'ABCMeta'
print(str(A)) # output: "<class '__main__.A'>"
print(str(B)) # output: "<class '__main__.B'>"
I expect that I should receive the output as below
print(A.__class__.__name__) # output: 'A'
print(B.__class__.__name__) # output: 'B'
The str(A)
and str(B)
seems to print the class name so I assume the class name can be extracted from somewhere. But nonetheless, I am not interested to use str
to parse and get the class name.
Python has a module called abc (abstract base class) that offers the necessary tools for crafting an abstract base class. First and foremost, you should understand the ABCMeta metaclass provided by the abstract base class. The rule is every abstract class must use ABCMeta metaclass.
The module we can use to create an abstract class in Python is abc(abstract base class) module. Here we just need to inherit the ABC class from the abc module in Python. To define an abstract method we use the @abstractmethod decorator of the abc module.
Introduction to Python Abstract Classes In object-oriented programming, an abstract class is a class that cannot be instantiated. However, you can create classes that inherit from an abstract class.
ABCMeta . i.e abc. ABC implicitly defines the metaclass for us. The only difference is that in the former case you need a simple inheritance and in the latter you need to specify the metaclass.
Recall that a metaclass is the type of a class, while a class is the type of its instances.
If we have a = A()
, a
is of type A
, and A
is of type abc.ABCMeta
. Therefore, you should naturally expect that A.__class__
and B.__class__
both return abc.ABCMeta
, since they are instances of it!
What you want is the names of A
and B
themselves, which you can get with A.__name__
and B.__name__
respectively.
Use just the __name__
property
print(A.__name__)
#A
A
in itself is a class, if you use A.__class__
you are getting it’s metaclass therefore it’s metaclass’ name.
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