Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) 
like image 321
parxier Avatar asked Mar 09 '10 04:03

parxier


People also ask

When should I use property decorator Python?

It is used to give "special" functionality to certain methods to make them act as getters, setters, or deleters when we define properties in a class.

How do you define a property in Python?

You can create a property by calling property() with an appropriate set of arguments and assigning its return value to a class attribute. All the arguments to property() are optional. However, you typically provide at least a setter function.

What are methods and properties in Python?

The property() method in Python provides an interface to instance attributes. It encapsulates instance attributes and provides a property, same as Java and C#. The property() method takes the get, set and delete methods as arguments and returns an object of the property class.


1 Answers

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 
like image 191
Toni Ruža Avatar answered Oct 04 '22 20:10

Toni Ruža