我必须检查 foo
是否是 myclass
的属性。
现在是我
def myclass():
try:
self.foo
except AttributeError:
self.foo = 'default'
当我认为我应该做的时候
if not hasattr(self,'foo'):
self.foo = 'default'
这两种方法之间有什么区别吗?应该首选哪一种?
我正在寻找以下条件:
- 与多重继承的一致性
- 跨python版本的可移植性
- 有限的开销
最佳答案
这两种方法在功能上是等效的。
来自 the hasattr
docs :
hasattr(object, name)
The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an AttributeError or not.)
和the getattr
docs说明如下:
getattr(x, 'foobar')
is equivalent tox.foobar
关于速度,我的测试表明 hasattr
稍快一些。 100 万次迭代的结果是:
hasattr: 0.6325701880014094 seconds
try: 0.8206841319988598 seconds
除非您正在编写高度优化的代码,否则无需担心这么小的差异。也无需担心与 python 版本的兼容性;属性访问和 hasattr
在每个版本的 python 中都可用。
最后,它归结为偏好。选择您认为更具可读性的那个。
关于python - 如何检查缺少的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49653108/