Are you looking for my non-technical blog?

This is now my technical-only blog, my non-technical blog is here.

23 June 2014

Python's Getters and Setters

You can read a better formatted version of this post here.

Just learn a new python feature called @property. Let's say we create a class called Circle 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()

See now.

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