为什么在访问Python对象属性时使用getattr()而不是__dict__? [英] Why use getattr() instead of __dict__ when accessing Python object attributes?
问题描述
在源示例和具有某种程度的Python对象自省的SO答案中,常见的模式是:
In source examples and SO answers that have some degree of Python object introspection, a common pattern is:
getattr(some_object, attribute_name_string)
是否有理由偏爱此模式?
Is there a reason why this pattern is preferred to:
some_object.__dict__[attribute_name_string]
哪个似乎更直接地显示出了什么情况?是因为后者太接近CPython中可能会更改的特定实现了吗?
which seems to be more directly showing what's going on? Is it because the latter is too close to a particular implementation in CPython that may be subject to change?
注意事项:原始问题错误地将流行用语标识为:
NB Original question incorrectly identified the popular idiom as:
some_object.__getattr__(attribute_name_string)
推荐答案
some_object.__getattr__
不是是常见的模式. getattr(some_object, attribute_name_string)
是动态访问属性的正确方法.
some_object.__getattr__
is not a common pattern. getattr(some_object, attribute_name_string)
is the proper way of accessing attributes dynamically.
并非所有实例具有一个__dict__
属性;例如,使用__slots__
的类将没有该属性.接下来,不一定在实例上 找到属性,而是类属性. getattr()
会找到那些,查看__dict__
不会找到它们.该类的属性也可能取决于描述符协议.
Not all instances have a __dict__
attribute; a class that uses __slots__
for example won't have that attribute. Next, attributes are not necessarily found on the instance, but are class attributes instead. getattr()
will find those, looking at __dict__
will not find them. Attributes on the class may also depend on the descriptor protocol.
可能有直接访问__getattr__
挂钩或__dict__
属性的用途,但这些只是专门用途.例如,仅当未在其他地方首次找到属性时才使用__getattr__
(因此,对于在类或instance.__dict__
中出现的不属性).
There may be uses for direct access to the __getattr__
hook or the __dict__
attribute, but those are specialised uses only. __getattr__
is only used if the attribute was not first found elsewhere, for example (so for attributes not present on the class or in instance.__dict__
).
这篇关于为什么在访问Python对象属性时使用getattr()而不是__dict__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!