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

后端 未结 6 1395
孤独总比滥情好
孤独总比滥情好 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:10

    In cases like these, I find it much better to choose the option that makes the most sense. You won't get any noticeable performance loss with small differences like these. It's much more important that your code is easy to use and maintain.

    As for choosing between using a method and a @property, it's a matter of taste, but since properties disguise themselves as simple attributes, nothing elaborate should be going on. A method indicates that it might be an expensive operation, and developers using your code will consider caching the value rather than fetching it again and again.

    So again, don't go on performance, always consider maintainability vs. performance. Computers get faster and faster as time goes by. The same does not stand for the readability of code.

    In short, if you want to get a simple calculated value, @property is an excellent choice; if you want an elaborate value calculated, a method indicates that better.

提交回复
热议问题