Python @property 与方法性能 - 使用哪一个? [英] Python @property versus method performance - which one to use?
问题描述
我编写了一些使用对象属性的代码:
I have written some code that uses attributes of an object:
class Foo:
def __init__(self):
self.bar = "baz"
myFoo = Foo()
print (myFoo.bar)
现在我想做一些花哨的计算来返回bar
.我可以使用 @property
使方法充当属性 bar
,或者我可以重构我的代码以使用 myFoo.bar()
.
Now I want to do some fancy calculation to return bar
. I could use @property
to make methods act as the attribute bar
, or I could refactor my code to use myFoo.bar()
.
我应该返回并为我所有的 bar
访问添加括号还是使用 @property
?假设我的代码库现在很小,但由于熵它会增加.
Should I go back and add parens to all my bar
accesses or use @property
? Assume my code base is small now but due to entropy it will increase.
推荐答案
如果它在逻辑上是对象的一个属性/属性,我会说保留它作为一个属性.如果它很可能被参数化,我的意思是你可能想要调用 myFoo.bar(someArgs)
那么现在就硬着头皮让它成为一个方法.
If it's logically a property/attribute of the object, I'd say keep it as a property. If it's likely to become parametrised, by which I mean you may want to invoke myFoo.bar(someArgs)
then bite the bullet now and make it a method.
在大多数情况下,性能不太可能成为问题.
Under most circumstances, performance is unlikely to be an issue.
这篇关于Python @property 与方法性能 - 使用哪一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!