36

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.field_1 + self.field_2

or

total = property(lambda self: self.field_1 + self.field_2)
parxier
  • 3,811
  • 5
  • 42
  • 54
  • 1
    Where have you seen this "property via lambda" that would cause you to think it could be "preferred"? Did you see a lot of these? If so, where? – S.Lott Mar 09 '10 at 11:01
  • @S.Lott Some python book, I don't remember. I will use decorators from now on. No problem. :-) – parxier Mar 10 '10 at 04:45

3 Answers3

51

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
Toni Ruža
  • 7,462
  • 2
  • 28
  • 31
  • 2
    I'm getting errors when using flake8, pyflakes when using this notation. I get redefinition of function 'elegant' warnings. – Stephan Sep 24 '12 at 10:08
  • With Pylint, there is an additional benefit to use the decorator. See [Pylint warning `W0212` with properties accessing a protected member: how to avoid?](http://stackoverflow.com/questions/24833362/pylint-warning-w0212-with-properties-accessing-a-protected-member-how-to-avoi). It preserves Pylint's ability to check the returned value/object. – Hibou57 Jul 18 '14 at 21:40
22

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.

Benno
  • 5,640
  • 2
  • 26
  • 31
5

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.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358