在python,del或delattr中哪个更好? [英] Which is better in python, del or delattr?
问题描述
这可能很愚蠢,但已经困扰了我一段时间.
This may be silly, but it's been nagging the back of my brain for a while.
Python为我们提供了两种从对象中删除属性的内置方法,即 del 命令字和 delattr 内置函数.我更喜欢 delattr ,因为我认为它更加明确:
Python gives us two built-in ways to delete attributes from objects, the del command word and the delattr built-in function. I prefer delattr because it I think its a bit more explicit:
del foo.bar
delattr(foo, "bar")
但是我想知道它们之间是否存在内在差异.
But I'm wondering if there might be under-the-hood differences between them.
推荐答案
第一个比第二个更有效. del foo.bar
编译为两个字节码指令:
The first is more efficient than the second. del foo.bar
compiles to two bytecode instructions:
2 0 LOAD_FAST 0 (foo)
3 DELETE_ATTR 0 (bar)
delattr(foo, "bar")
需要五个:
2 0 LOAD_GLOBAL 0 (delattr)
3 LOAD_FAST 0 (foo)
6 LOAD_CONST 1 ('bar')
9 CALL_FUNCTION 2
12 POP_TOP
这意味着第一次运行稍快更快(但这并不是一个很大的差异–在我的计算机上为.15μs).
This translates into the first running slightly faster (but it's not a huge difference – .15 μs on my machine).
就像其他人所说的那样,您真正应该只在动态确定要删除的属性时才使用第二种形式.
Like the others have said, you should really only use the second form when the attribute that you're deleting is determined dynamically.
这篇关于在python,del或delattr中哪个更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!