What is Property()?

When reading Python code you may have seen the following:

class MyClass(object):
    def __init__(self):
        pass

    @property
    def do_something(self):   
        return True

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 the three methods that handle requests to read, write, or delete that attribute.[1]

Getter

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

class Interface(object):
    def __init__(self):
        self._speed = 100
        
    @property
    def speed(self):   
        print('called getter')
        return self._speed

We can then get our property, like so.

>>> interface = Interface()
>>> interface.speed
called getter
100

Setter

The setter, expressed as @<property_name>.setter, allows us set (update) the property.

Based on our previous example let’s see what happens when we try to set our property.

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

Now let us use a setter to achieve the same. First let us add the setter.

class Interface(object):
    def __init__(self):
        self._speed = 100
    
    @property
    def speed(self):   
        print('called getter')
        return self._speed
    
    @speed.setter
    def speed(self, interface_speed):   
        print('called setter')
        if interface_speed > 200:
            raise ValueError('speed is greater than 1000')
        return self._speed

Let us now retest.

>>> interface = Interface()
>>> interface.speed
called getter
100

>>> interface.speed = 200
called setter
>>> interface.speed
called getter
200

>>> interface.speed = 10000
called setter
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 12, in speed
ValueError: speed is greater than 1000

References


  1. "21.15. property(): Create an access-controlled attribute." 24 Apr. 2013, https://infohost.nmt.edu/tcc/help/pubs/python/web/property-function.html. Accessed 19 Jun. 2019. ↩︎