Thursday, March 12, 2015

Descriptors in Python

For me at least, descriptor is one of the under used features of core Python. Normally, Python just gets and sets values on attributes without any special processing. It’s just basic storage. Sometimes, however, you may want to do more. May be, you need to validate the value that’s being assigned to an attribute. You can use descriptors for this.

Descriptors are implemented as a standard new-style class in Python, and you need to inherit object to use it. Following is an easy example for custom descriptor.

class Movie(object):
    def __init__(self, budget, gross):
        self._budget = None
        self._gross = None

 
    @property
    def profit(self):
        return (self.gross - self.budget)

 
    @property
    def budget(self):
        return self._budget

    @budget.setter
    def budget(self, value):
        if value < 0:
            raise ValueError("Negative value not allowed: %s" % value)
        self._budget = value

    @property
    def gross(self):
        return self._gross

    @gross.setter
    def gross(self, value):
        if value < 0:
            raise ValueError("Negative value not allowed: %s" % value)
        self._gross = value

obj = Movie(3, 10)
obj.budget = -5
obj.gross = 10

print obj.profit


In the above example,  obj.profit returns the difference between gross and budget instead of the method object.

1 comment:

  1. Hard Rock Hotel Casino & Spa, Hollywood, FL, USA - Mapyro
    Realtime driving 동두천 출장샵 directions to 구미 출장샵 Hard Rock Hotel Casino & Spa, Hollywood, FL, USA, based 충주 출장안마 on live traffic updates and road conditions 고양 출장안마 – from 남양주 출장마사지 US traffic

    ReplyDelete