2017-07-12 14 views
2
n = 20 
print n.__name__ 

nは何の属性__name__を持っていないように私はエラーを取得しています:type(n).__ name__が機能するときにn .__ name__属性エラーが発生するのはなぜですか?

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

しかしnintクラスのインスタンスであり、int.__name__は結果を与える、なぜn.__name__はエラーをスローしません。 nはクラスintのインスタンスなので、そのクラスのすべての属性にアクセスできるはずです。

+0

"nはクラスintのインスタンスであり、intクラスのすべての属性にアクセスできる必要があるため、それは動作しません。 Pythonは 'n'のメソッド解決順序で '__name__'のすべてのクラスのクラスdictsを検索しますが、' int .__ name__'は 'int .__ dict__'のエントリから来ません。 – user2357112

答えて

6

__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(それはdescriptorなので、にバインドされていますintにアクセスintクラス):

>>> type(int) 
<type 'type'> 
>>> type.__dict__['__name__'] 
<attribute '__name__' of 'type' objects> 
>>> type.__dict__['__name__'].__get__(int) 
'int' 

ただ、インスタンスの属性ルックアップのようなことができますクラスを見ると、クラスの属性ルックアップはメタクラスの属性を探します。

メタクラスの属性は、クラスのインスタンスでは使用できません。

関連する問題