Get fully qualified name of a Python class (Python

2019-02-21 19:48发布

问题:

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.

回答1:

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))