how.wtf

Getters and setters in Python

· Thomas Taylor

Writing getter and setter methods in Python is seamless using the @property decorator.

Using the @property decorator for getter and setter methods

Directly from the documentation:

 1class C(object):
 2    def __init__(self):
 3        self._x = None
 4
 5    @property
 6    def x(self):
 7        """I'm the 'x' property."""
 8        print("getter of x called")
 9        return self._x
10
11    @x.setter
12    def x(self, value):
13        print("setter of x called")
14        self._x = value
15
16    @x.deleter
17    def x(self):
18        print("deleter of x called")
19        del self._x
20
21
22c = C()
23c.x = 'foo'  # setter called
24foo = c.x    # getter called
25del c.x      # deleter called

An implementation of this method could be a product where a user can set a price after its instantiation.

 1class Product:
 2    def __init__(self, name):
 3        self._name = name
 4
 5    @property
 6    def price(self):
 7        return self._price
 8
 9    @price.setter
10    def price(self, new_price):
11        if new_price < 0 or not isinstance(new_price, float):
12            raise Exception("price must be greater than 0 and a float")
13        self._price = new_price
14
15    @price.deleter
16    def price(self):
17        del self._price
18
19
20p1 = Product("one")
21p1.price = 5.5

#python  

Reply to this post by email ↪