问题描述
一个有点笨拙的最佳实践问题.我习惯使用object.__dict__[some_key]
动态查找对象属性值.现在我想知道哪个更好/更快:我现在的习惯或getattr(object,some_key)
.如果一个更好,为什么?
A somewhat noobish, best practice question. I dynamically look up object attribute values using object.__dict__[some_key]
as a matter of habit. Now I am wondering which is better/faster: my current habit or getattr(object,some_key)
. If one is better, why?
>>> class SomeObject:
... pass
...
>>> so = SomeObject()
>>> so.name = 'an_object'
>>> getattr(so,'name')
'an_object'
>>> so.__dict__['name']
'an_object'
推荐答案
使用getattr()
而不是直接进入__dict__
结构会更好.
You are much better off using getattr()
instead of going directly to the __dict__
structure.
不是因为它更快或更慢,而是因为官方API在 all 的所有情况下都能正常工作,包括对于 not 没有__dict__
的类(使用 __slots__
),或者当对象实现 __getattr__
或 __getattribute__
挂钩,或者当相关属性为描述符(例如 property
)或类属性.
Not because it's faster or slower, but because the official API works in all circumstances, including for classes that do not have a __dict__
(when using __slots__
for example), or when an object implements the __getattr__
or __getattribute__
hooks, or when the attribute in question is a descriptor (such as a property
), or a class attribute.
如果您想知道某条python语句或技术是否比另一条更快,请使用 timeit
模块来测量差异:
If you want to know if any one python statement or technique is faster than another, use the timeit
module to measure the difference:
>>> import timeit
>>> class Foo(object):
... pass
...
>>> foo = Foo()
>>> foo.bar = 'spam'
>>> timeit.timeit("getattr(foo, 'bar')", 'from __main__ import foo')
0.2125859260559082
>>> timeit.timeit("foo.__dict__['bar']", 'from __main__ import foo')
0.1328279972076416
您可以看到直接访问__dict__
的速度更快,但是getattr()
的工作量更大.
You can see that directly accessing __dict__
is faster, but getattr()
does a lot more work.
这篇关于getattr()与dict查找,哪个更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!