Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between @property and property()

Is there a difference between

class Example(object):
    def __init__(self, prop):
        self._prop = prop

    def get_prop(self):
        return self._prop

    def set_prop(self, prop):
        self._prop = prop

    prop = property(get_prop, set_prop)

and

class Example2(object):
    def __init__(self, prop):
        self._prop = prop

    @property
    def prop(self):
        return self._prop

    @prop.setter
    def prop(self, prop):
        self._prop = prop

They seem to do the same thing, which doesn't fit python's goal of there being only one obvious way to do things. Is there a prefered way? And if so, why?

like image 483
BoshWash Avatar asked Feb 14 '23 11:02

BoshWash


1 Answers

The @decorator syntax is just syntactic sugar. There are no differences between the two approaches other than the syntax, the end result is the same.

@property
def prop(self):
    return self._prop

is translated to:

def prop(self):
    return self._prop
prop = property(prop)

and the same applies to the setter:

@prop.setter
def prop(self, prop):
    self._prop = prop

becomes:

tmp = prop.setter
def prop(self, prop):
    self._prop = prop
prop = tmp(prop)

as the decorator expression (prop.setter) is evaluated first. See How does the @property decorator work? for how .setter() (and .deleter() and .getter()) works.

Note that the prop.setter() decorator (and the .getter() and .deleter() decorators) of property objects was only added in Python 2.6. In addition, property was added to Python in version 2.2, but decorators were only added to the language in Python 2.4.

As a result, a lot of documentation still uses the older property constructor method.

If you are coding for Python 2.6 or newer, however, you should be using the decorators syntax.

The @property and @prop.setter decorators give a clear early visual signal that you have property functions here, while the separate prop = property(...) line after the property functions is easily missed, especially if the property implementation is longer.

like image 156
Martijn Pieters Avatar answered Feb 16 '23 04:02

Martijn Pieters