Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching python class name while using abstract classes with `abc` library

Tags:

python

abc

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.

like image 700
Praveen Kulkarni Avatar asked May 27 '19 05:05

Praveen Kulkarni


People also ask

What is ABC abstract class in Python?

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.

Which class should a class inherit from abstract in Python?

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.

Can we inherit abstract class in Python?

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.

What is the difference between ABC and ABCMeta?

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.


Video Answer


2 Answers

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.

like image 61
gmds Avatar answered Sep 20 '22 19:09

gmds


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.

like image 34
Jab Avatar answered Sep 21 '22 19:09

Jab