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.
__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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With