Using getattr in python

血红的双手。 提交于 2021-02-10 20:30:46

问题


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 to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

Which method does getattr() call? For example, does it call:

  • __getattr__
  • __get__
  • __getattribute__
  • something else?

回答1:


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.



来源:https://stackoverflow.com/questions/58533959/using-getattr-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!