fir3net

Sponsored by

PPS Logo Red 200mm

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]

Getter

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

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

We then get our property, like so.

>>> a = Account()
>>> a.total
called getter
100

Setter

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

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

>>> a.total = 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,

>>> a.total = 22
called setter

>>> a.total = 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
>>>

References

[1] https://infohost.nmt.edu/tcc/help/pubs/python/web/property-function.html

Links

http://stackoverflow.com/questions/9920677/how-should-i-expose-read-only-fields-from-python-classes

Tags: Python

About the Author

RDonato

R Donato

Ricky Donato is the Founder and Chief Editor of Fir3net.com. He currently works as a Principal Network Security Engineer and has a keen interest in automation and the cloud.

You can find Ricky on Twitter @f3lix001