繁体   English   中英

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

[英]How do I get the string with name of a class?

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

In [1]: class Test:
   ...:     pass
   ...: 

In [2]: Test.__name__
Out[2]: 'Test'

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

我同意鲨鱼先生的观点,但如果你有一个类的实例,你需要使用它的__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>

Python 3.3起,我们可以对类和函数使用__qualname__字段

它与嵌套对象的__name__字段不同,例如在其他类中定义的类

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

这可能非常有用。

进一步阅读

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

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

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

或者,如前所述,

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM