Python @property versus method performance - which one to use?

后端 未结 6 1499
孤独总比滥情好
孤独总比滥情好 2021-01-04 03:31

I have written some code that uses attributes of an object:

class Foo:
    def __init__(self):
        self.bar = \"baz\"
myFoo = Foo()
print (myFoo.bar)
         


        
6条回答
  •  梦谈多话
    2021-01-04 04:12

    I agree with what most people here have said, I did much measurement when building hydrologic models in Python a couple years ago and found that the speed hit from using @property was completely overshadowed by calculation.

    As an example, creating method local variables (removing the "dot factor" in my calculations increased performance by almost an order of magnitude more than removing @property (these results are averaged over a mid-scale application).

    I'd look elsewhere for optimization, when it's necessary, and focus initially on getting good, maintainable code written. At this point, if @property is intuitive in your case, use it. If not, make a method.

提交回复
热议问题