18

Possible Duplicate:
Real world example about how to use property feature in python?

I have a question about the decorator @property that I've seen in the following code. Could someone be kind enough to completely explain why someone would use the @property decorator? I know @property is equivalent to isActive = property(isActive) but what does the method property actually do to it's parameter? If I were to call the isActive method from the InputCell class what would actually happen? Thanks in advance.

class InputCell(object):
    def __init__(self, ix, iy, inputData):
        self.ix = ix
        self.iy = iy
        self.InputData = inputData

    @property
    def isActive(self):
        return self.InputData[self.ix][self.iy]
Community
  • 1
  • 1
letter Q
  • 14,735
  • 33
  • 79
  • 118
  • 2
    The documentation for the decorator actually explains this in the third sentence: http://docs.python.org/py3k/library/functions.html?highlight=property#property – millimoose Jul 16 '12 at 22:51
  • (If you were to call `InputCell().isActive()` you'd likely get an exception saying whatever the value of `inputData[ix][iy]` is isn't callable.) – millimoose Jul 16 '12 at 22:52
  • 5
    A @property is used to make a function look like an attribute. You can use this to make sure certain operations are carried out whenever a property is accessed. For example, if you have a ton of code that uses an angle parameter expressed in degrees, then later decide that internally you want to track the angle in radians, you can create property methods that hide the fact that radians are in use internally. – Russell Borogove Jul 16 '12 at 23:02
  • I realize this is old, but you forgot to capitalize the 'i' in the last line. It should be return self.InputData[self.ix][self.iy] – Erotemic Mar 14 '13 at 15:52

1 Answers1

25

It's simply syntactic sugar. It allows a method call to look like a variable access or assignment.

One way this can be useful is if you want to change something that previously was a simple variable to something that's actually computed or validated with other code. If you make it a property, you can do this without breaking any existing code. Another way is for caching, lazy initialization, etc., of object attributes.

Taymon
  • 24,950
  • 9
  • 62
  • 84