[PYTHON] Get the class name without creating an instance

Overview

There was no Japanese article that describes how to get the class name from the class object itself, so I will write it as a memorandum.

How to get the class name

Get from instance

Even if I googled, most of them were obtained using this method.

class A:
  pass

a = A()
print(a.__class__.__name__)
>>> A

Get from the class object itself

You can get it with __qualname__ implemented from Python 3.3. Postscript: It seems that you can also get it with B.__name__. Thank you, @shiracamus. Also, __qualname__ can be simply written as __qualname__ instead of B.__qualname__ in a class object.

class B:
  pass

print(B.__qualname__)
>>> B

#Postscript
class C:
  qualname = __qualname__

print(C.__name__)
print(C.qualname)
>>> C
>>> C

in conclusion

If it is ~~ __qualname__, you can get it in the class object or in the function that takes the class object as an argument. ~~ Addendum: As I added earlier, it seems that you can also get it by using __name__.

References

[Get the name of the current class? ](Https://www.it-swarm.dev/ja/python/ Get the name of the current class? /940596062/)

Recommended Posts

Get the class name without creating an instance
Creating an HTTP Get box
Get the class name where the method is defined in the decorator
Get the attributes of an object
Get the host name in Python
[Python] Get the variable name with str
Python: Prepare a serializer for the class instance:
Get an access token for the Pocket API
[Python] class, instance
Python class, instance
Don't take an instance of a Python exception class directly as an argument to the exception class!
How to get the variable name itself in python
Get the variable name of the variable as a character string.
Get the file name in a folder using glob
Users without an account access the AWS Management Console
Get swagger.json with Flask-RESTX (Flask-RESTPlus) without starting the server
Decrease the class name of the detection result display of object detection
python (2) requires self because the method is an instance method