Properties

Properties

I always have troubles remembering Properties in Python so this time I am going to document it so it is easily available to me next time I want to review the topic. Hopefully, it also helps someone else.

Suppose I create a simple Class as below:

And this works as expected:

Notice the attribute radius stored as instance attribute when we call the __dict__ method on the instance.

Now, someone else creates a new class NewCircle and inherits the Circle class.

And this works as expected. The instance of class NewCircle can call its local method perimeter as well as the get_diameter method from the parent class Circle.

Notice that instance attribute is exposed (radius in this case) and we can set it to a different value.

Suppose that we are given a requirement that the radius value cannot be set more than 50 and the radius input value must be float. This can be achieved using Property by adding getter and setter methods in the Circle class.

The refactored Circle class will look like this:

Now, when we create a new instance of class NewCircle, notice that the setter method is called as soon the compiler hits self.radius = radius statement in the initializer method.

Also, notice that when a value is passed during intialization (or set with <instance>.radius call), the setter method is called which stores the passed value to self._radius. When we do a lookup for radius attribute on the instance, the getter method is called which returns the value of self._radius.