Why do python instances have no __name__ attribute?
Asked Answered
H

1

24
>>> class Foo:
...   'it is a example'
...   print 'i am here'
... 
i am here
>>> Foo.__name__
'Foo'
>>> Foo().__name__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Foo instance has no attribute '__name__'
>>> Foo.__doc__
'it is a example'
>>> Foo().__doc__
'it is a example'
>>> Foo.__dict__
{'__module__': '__main__', '__doc__': 'it is a example'}
>>> Foo().__dict__
{}
>>> Foo.__module__
'__main__'
>>> Foo().__module__
'__main__'
>>> myname=Foo()
>>> myname.__name__
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: Foo instance has no attribute `__name__`

What is the reason instances have no attribute __name__?
maybe it is ok that the __name__ of instance-myname is myname.
would you mind tell me more logical, not the unreasonable grammar rules?

Hominoid answered 25/1, 2013 at 3:24 Comment(3)
What makes you think there is supposed to be a __name__ attribute on instances? The relevant documentation says it exists for classes (and other things), but I don't see any mention of it for instances.Dulcie
From the docs: __name__ is the name of a "class or type", not an instance of a class or type. Why should instances have __name__s?Alcott
Did you mean Foo().__class__.__name__ ?Feu
J
33

You're seeing an artifact of the implementation of classes and instances. The __name__ attribute isn't stored in the class dictionary; therefore, it can't be seen from a direct instance lookup.

Look at vars(Foo) to see that only __module__ and __doc__ are in the class dictionary and are visible to the instance.

For the instance to access the name of a class, it has to work its way upward with Foo().__class__.__name__. Also note that classes have other attributes such as __bases__ that aren't in the class dictionary and likewise cannot be directly accessed from the instance.

Jovanjove answered 25/1, 2013 at 3:37 Comment(1)
I understand that is is dynamically set on the class during runtime. However, my IDE (PyCharm) is complaining about this error. Is there any way to avoid this without disabling Type checking?Lilt

© 2022 - 2024 — McMap. All rights reserved.