Properties


A property is a special kind of attribute that has a getter, setter (and deleter method). It allows us to define a method but access it like an attribute. This is useful when we want to add some logic to the getting or setting of an attribute.

Let’s consider our typical beam. We want to calculate the volume of the beam. We can use a A property to do this.

How to create properties


class Beam:
    def __init__(self, length=2, width=0.2, height=0.5):
        self.length = length
        self.width = width
        self.height = height
        self._volume = None  # we use _ to indicate that this is a private attribute

    # this is the getter method
    @property  # this is a decorator needed to define a property
    def volume(self):
        self._volume = self.length * self.width * self.height
        return self._volume

    # this is the setter method
    @volume.setter  # this is a decorator needed to define a setter
    def volume(self, dimensions):
        length, width, height = dimensions
        self.length = length
        self.width = width
        self.height = height


How to use properties


# create the beam
beam = Beam()

# get the volume
print(beam.volume)  # 0.2

# set the volume
beam.volume = 3, 0.3, 0.6

# get the volume
print(beam.volume)  # 0.54


🛠 Exercise


🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍

Solution:

🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍