Python - What does Property() do ?

What is Property()?

The purpose of this function is to create a property of a class. A property looks and acts like an ordinary attribute, except that you provide methods that control access to the attribute.
There are three kinds of attribute access: read, write, and delete. When you create a property, you can provide any or all of three methods that handle requests to read, write, or delete that attribute.[1]


To provide read access only to the property of the class, @property is used.

class Account(object):
    def __init__(self):
        self._total = 100
        self._amount = 200

    def total(self):   
        print 'called getter'
        return self._total

We then get our property, like so.

>>> a = Account()
called getter


First of all , what happens if we try to set our property? Lets see,

>>> a._amount = 150
>>> a._amount

>>> = 150
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

As you can see assignment of _amount completes, however we are unable to assign our class property -- total.
In order to set the property we will need to add @<property_name>.setter, like so.


@total.setter def total(self, value): print 'called setter' if value > 200: raise ValueError('value is greater than 200') else: self._total = value

Now, this provides us the ability to set, but also the power to mandate type control. Here's an example,

>>> = 22
called setter

>>> = 220
called setter
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 14, in total
ValueError: value is greater than 200




Tags: Python