Why is n.__name__ an attribute error when type(n).__name__ works?

允我心安 提交于 2019-12-04 04:10:22

问题


n = 20
print n.__name__

I am getting an error as n has no attribute __name__:

AttributeError: 'int' object has no attribute '__name__'

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.


回答1:


__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.



来源:https://stackoverflow.com/questions/45064509/why-is-n-name-an-attribute-error-when-typen-name-works

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