getattr()
转到
__getattribute__()
首先,与点运算符相同:
>>> 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__
惯例是使用
获取属性()
只有在编译时不知道属性名应该是什么的时候。如果你这样做了,那么使用点运算符(“显式优于隐式”…)。
正如@klaus d.在评论中提到的,
the python Data Model documentation
更详细地说明
.__getattribute__()
和
.__getattr__()
互动。可以说,在高水平上,后者是一种退却的选择,因为如果前者失败了。请注意
.\uu getattr_uuu()
以及内置的
获取属性()
不是直接相关的-iirc这是一个命名的怪癖,起源于早期版本的python,并被赋予到python 3中。