Preferred way of defining properties in Python: property decorator or lambda?

前端 未结 3 1214
灰色年华
灰色年华 2020-12-24 12:47

Which is the preferred way of defining class properties in Python and why? Is it Ok to use both in one class?

@property
def total(self):
    return self.fiel         


        
相关标签:
3条回答
  • 2020-12-24 13:08

    For read-only properties I use the decorator, else I usually do something like this:

    class Bla(object):
        def sneaky():
            def fget(self):
                return self._sneaky
            def fset(self, value):
                self._sneaky = value
            return locals()
        sneaky = property(**sneaky())
    

    update:

    Recent versions of python enhanced the decorator approach:

    class Bla(object):
        @property
        def elegant(self):
            return self._elegant
    
        @elegant.setter
        def elegant(self, value):
            self._elegant = value
    
    0 讨论(0)
  • 2020-12-24 13:21

    The decorator form is probably best in the case you've shown, where you want to turn the method into a read-only property. The second case is better when you want to provide a setter/deleter/docstring as well as the getter or if you want to add a property that has a different name to the method it derives its value from.

    0 讨论(0)
  • 2020-12-24 13:34

    Don't use lambdas for this. The first is acceptable for a read-only property, the second is used with real methods for more complex cases.

    0 讨论(0)
提交回复
热议问题