Get fully qualified name of a Python class (Python 3.3+)

偶尔善良 提交于 2019-12-08 17:00:34

问题


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


来源:https://stackoverflow.com/questions/37568128/get-fully-qualified-name-of-a-python-class-python-3-3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!