11

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.

Praveen Kulkarni
  • 2,816
  • 1
  • 23
  • 39

2 Answers2

10

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.

gmds
  • 19,325
  • 4
  • 32
  • 58
4

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.

Jab
  • 26,853
  • 21
  • 75
  • 114