Python Getters & Setters

Solving the problem of objects variable setting using the @property decorator


Let's say we create a class called Square as follows.

class Square:
  
  side = 2
  area = side * side

s = Square()
        

Now:

>>> s.side
2
>>> s.area
4
        

However:

>>> s.side = 3
>>> s.side
3
>>> s.area
4
        

Not cool! How to solve that?

class Square:
  
  side = 2
  
  @property
  def area(self):
    return self.side * self.side

s = Square()
        

Now:

>>> s.side = 3
>>> s.side
3
>>> s.area
9
        

The @property decorator turns the area() method into a “getter” for a read-only attribute with the same name. In other words, the decorator allows a method call to look like a variable access, so now we can let the area value be recalculated everytime the method is called using the updated value of side.

And yes, you guessed it right, there is also @area.setter and @area.deleter decorators for turing the area() method into a “setter” and “deleter” too.




Share on Facebook Share on twitter