How can I get name of class including full path from its module root? For Python 3.3 and up?
Here is example of Python code:
class A:
class B:
class C:
def me(self):
print(self.__module__)
print(type(self).__name__)
print(repr(self))
x = A.B.C()
x.me()
This code outputs me on Python 3.3:
__main__
C
<__main__.A.B.C object at 0x0000000002A47278>
So, Python internally knows that my object is __main__.A.B.C
, but how can I get this programmatically? I can parse repr(self)
, but it sounds like a hack for me.
A class is a data structure, and it can hold both data members and member methods. This tutorial will discuss the method to get the class name in Python. type () is a predefined function that can be used in finding the type or class of an object.
Use the __class__ and __name__ Properties to Get the Type or Class of an Object/Instance The __class__ property can also be used to find the class or type of an object. It basically refers to the class the object was created in. The __name__ can also be used along with __class__ to get the class of the object.
“Qualified name” is the best approximation, as a short phrase, of what the additional attribute is about. It is not a “full name” or “fully qualified name” since it (deliberately) does not include the module name. Calling it a “path” would risk confusion with filesystem paths and the __file__ attribute.
You are looking for __qualname__
(introduced in Python 3.3):
class A:
class B:
class C:
def me(self):
print(self.__module__)
print(type(self).__name__)
print(type(self).__qualname__)
print(repr(self))
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