Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python property decorator [duplicate]

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]
like image 434
Wang-Zhao-Liu Q Avatar asked Jul 16 '12 22:07

Wang-Zhao-Liu Q


People also ask

What is true about property decorator?

@property decorator is a built-in decorator in Python which is helpful in defining the properties effortlessly without manually calling the inbuilt function property(). Which is used to return the property attributes of a class from the stated getter, setter and deleter as parameters.

What does the property decorator do Python?

The @property is a built-in decorator for the property() function in 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.

Are very similar to property decorators but are used for methods instead?

Method decorators are very similar to property decorators but are used for methods instead. This let's us decorate specific methods within our class with functionality. A good example of this is @HostListener .

What is the difference between an attribute and a property in Python?

Attributes are described by data variables for example like name, age, height etc. Properties are special kind of attributes which have getter, setter and delete methods like __get__, __set__ and __delete__ methods.


1 Answers

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.

like image 57
Taymon Avatar answered Oct 04 '22 00:10

Taymon