Why use getattr() instead of __dict__ when accessing Python object attributes?

烈酒焚心 提交于 2019-12-11 04:07:06

问题


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]

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)

回答1:


some_object.__getattr__ is not a common pattern. getattr(some_object, attribute_name_string) is the proper way of accessing attributes dynamically.

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.

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__).



来源:https://stackoverflow.com/questions/27819819/why-use-getattr-instead-of-dict-when-accessing-python-object-attributes

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