为什么当type(n).__ name__工作时n .__ name__是一个属性错误? [英] Why is n.__name__ an attribute error when type(n).__name__ works?
问题描述
n = 20
print n.__name__
我遇到错误,因为n
没有属性__name__
:
I am getting an error as n
has no attribute __name__
:
AttributeError: 'int' object has no attribute '__name__'
但是n
是int
类的实例,而int.__name__
给出结果,所以为什么n.__name__
会引发错误.我期望由于n
是类int
的实例,因此它应该有权访问该类的所有属性.
But n
is an instance of the int
class, and int.__name__
gives a result, so why does n.__name__
throw an error. I expected that because n
is an instance of class int
, it should have access to all attributes of that class.
推荐答案
__name__
不是int
类(或其任何基类)的属性:
__name__
is not an attribute on the int
class (or any of its base classes):
>>> 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__'
It is an attribute on the metaclass, type
(it is a descriptor, so is bound to the int
class when accessed on int
):
>>> type(int)
<type 'type'>
>>> type.__dict__['__name__']
<attribute '__name__' of 'type' objects>
>>> type.__dict__['__name__'].__get__(int)
'int'
就像实例上的属性查找也可以查看类一样,类上的属性查找也可以查看元类上的属性.
Just like attribute look-up on an instance can also look at the class, attribute lookup on a class looks for attributes on the metaclass.
元类的属性在类的实例上不可用.
Attributes on the metaclass are not available on instances of the class.
这篇关于为什么当type(n).__ name__工作时n .__ name__是一个属性错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!