Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 921
Amarnath Reddy Avatar asked Jan 31 '23 00:01

Amarnath Reddy


1 Answers

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

like image 151
Martijn Pieters Avatar answered Feb 02 '23 08:02

Martijn Pieters