为什么当type(n).__ name__工作时n .__ name__是一个属性错误? [英] Why is n.__name__ an attribute error when type(n).__name__ works?

查看:137
本文介绍了为什么当type(n).__ name__工作时n .__ name__是一个属性错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

但是nint类的实例,而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__'

它是元类type上的一个属性(它是

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆