Why does object
seem not to have a __getattr__
method? It defines both __setattr__
and __delattr__
. Doesn't it need all three?
>>> object.__setattr__
<slot wrapper '__setattr__' of 'object' objects>
>>>
>>> object.__delattr__
<slot wrapper '__delattr__' of 'object' objects>
>>>
>>> object.__getattr__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'object' has no attribute '__getattr__'
>>> sys.version
'2.7.3 (default, Feb 27 2014, 19:58:35) \n[GCC 4.6.3]'
Python getattr() function is used to get the value of an object's attribute and if no attribute of that object is found, default value is returned.
The getattr() method returns the value of the named attribute of an object. If not found, it returns the default value provided to the function.
1 Answer. The main difference between __getattr__ and __getattribute__ is that if the attribute was not found by the usual way then __getattr__ is used. Whereas the __getattribute__ is used before looking at the actual attributes on the object.
Indeed, object
does not have a __getattr__
method.
>>> import pprint
>>> pprint.pprint(dir(object))
['__class__',
'__delattr__',
'__doc__',
'__format__',
'__getattribute__',
'__hash__',
'__init__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__']
Instead, it has __getattribute__
.
>>> object.__getattribute__
<slot wrapper '__getattribute__' of 'object' objects>
https://docs.python.org/2/reference/datamodel.html#object.__getattribute__
explains why:
object.__getattribute__(self, name)
Called unconditionally to implement attribute accesses for instances of the class. If the class also defines
__getattr__()
, the latter will not be called unless__getattribute__()
either calls it explicitly or raises anAttributeError
.
In other words, if you have __getattribute__
, it doesn't make sense to also define __getattr__
.
Historically, __getattr__
came first, and __getattribute__
was introduced with "new-style classes" in Python 2.3 (iirc). Python 3 only has new-style classes but seems to have preserved both hooks anyway (perhaps because it can be convenient to have a hook that is only called if "normal attribute access" fails).
__getattr__
is a method that runs only after __getattribute__
. Since object
has the latter, there is technically no need for the former. But in general, you shouldn’t expect object
to have all the things that other objects (deriving from it) have. Since object
is implemented in native code, it may behave a bit differently.
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