n = 20
print n.__name__
我收到错误如下n
没有属性__name__
:
AttributeError: 'int' object has no attribute '__name__'
But n
是一个实例int
类,以及int.__name__
给出了结果,那么为什么n.__name__
抛出一个错误。我预料到了,因为n
是类的一个实例int
,它应该可以访问该类的所有属性。
__name__
不是一个属性int
类(或其任何基类):
>>> int.__dict__['__name__']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: '__name__'
>>> int.__mro__
(<class 'int'>, <class 'object'>)
>>> object.__dict__['__name__']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: '__name__'
它是一个属性元类, type
(它是一个描述符 https://docs.python.org/3/howto/descriptor.html,所以必然是int
访问时的类int
):
>>> type(int)
<type 'type'>
>>> type.__dict__['__name__']
<attribute '__name__' of 'type' objects>
>>> type.__dict__['__name__'].__get__(int)
'int'
就像实例上的属性查找也可以查看类一样,类上的属性查找会查找元类上的属性。
元类的属性在类的实例上不可用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)