Reputation: 705
The getattr
function is defined as follows:
getattr(object, name[, default])
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example,
getattr(x, 'foobar')
is equivalent tox.foobar
. If the named attribute does not exist, default is returned if provided, otherwiseAttributeError
is raised.
Which method does getattr()
call? For example, does it call:
__getattr__
__get__
__getattribute__
Upvotes: 3
Views: 1449
Reputation: 24681
getattr()
goes to __getattribute__()
first, same as the dot operator:
>>> class A:
... def __getattr__(self, obj):
... print("Called __getattr__")
... return None
... def __getattribute__(self, obj):
... print("Called __getattribute__")
... return None
... def __get__(self, obj):
... print("Called __get__")
... return None
...
>>> a = A()
>>> a.foobar
Called __getattribute__
>>> getattr(a, 'foobar')
Called __getattribute__
Convention is to use getattr()
only when you don't know at compile-time what the attribute name is supposed to be. If you do, then use the dot operator ("explicit is better than implicit"...).
As @Klaus D. mentioned in a comment, the python Data Model documentation goes into more detail about how .__getattribute__()
and .__getattr__()
interact. Suffice it to say that, at a high level, the latter is a fall-back option of sorts for if the former fails. Note that .__getattr__()
and the built-in getattr()
are not directly related - IIRC this is a quirk of naming that originated in earlier versions of python and was granfathered into python 3.
Upvotes: 4