代码之家  ›  专栏  ›  技术社区  ›  clahey

如何获取带有类名的字符串?

  •  53
  • clahey  · 技术社区  · 17 年前

    我应该调用什么方法来获取类的名称?

    5 回复  |  直到 7 年前
        1
  •  61
  •   Mr Shark    17 年前
    In [1]: class Test:
       ...:     pass
       ...: 
    
    In [2]: Test.__name__
    Out[2]: 'Test'
    
        2
  •  43
  •   clahey    17 年前

    这不是一种方法,而是一个领域。该字段名为 __name__ . class.__name__ 将以字符串形式给出类的名称。 object.__class__.__name__ 将给出对象类的名称。

        3
  •  12
  •   David C Rodrigo Deodoro    13 年前

    我同意Shark先生的观点,但如果你有一个类的实例,你需要使用它的 __class__ 成员:

    >>> class test():
    ...     pass
    ...
    >>> a_test = test()
    >>>
    >>> a_test.__name__
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: test instance has no attribute '__name__'
    >>>
    >>> a_test.__class__
    <class __main__.test at 0x009EEDE0>
    
        4
  •  1
  •   Vlad the Impala    15 年前

    来自 Python 3.3 从那时起,我们可以使用 __qualname__ field 对于这两个类&;功能。

    它不同于 __name__ field 用于嵌套对象,如其他类中定义的类

    >>> class A:
            class B:
                pass
    >>> A.B.__name__
    'B'
    >>> A.B.__qualname__
    'A.B'
    

    这可能非常有用。

    进一步阅读

        5
  •  1
  •   Azat Ibrakov    7 年前

    在[8]中: str('2'.__class__)
    输出[8]: "<type 'str'>"

    在[9]中: str(len.__class__)
    出[9]: "<type 'builtin_function_or_method'>"

    在[10]中: str(4.6.__class__)
    输出[10]: "<type 'float'>"

    或者,如前所述,

    在[11]中: 4.6.__class__.__name__
    退出[11]: 'float'