Real world example about how to use property feature in python? Real world example about how to use property feature in python? python python

Real world example about how to use property feature in python?


Other examples would be validation/filtering of the set attributes (forcing them to be in bounds or acceptable) and lazy evaluation of complex or rapidly changing terms.

Complex calculation hidden behind an attribute:

class PDB_Calculator(object):    ...    @property    def protein_folding_angle(self):        # number crunching, remote server calls, etc        # all results in an angle set in 'some_angle'        # It could also reference a cache, remote or otherwise,        # that holds the latest value for this angle        return some_angle>>> f = PDB_Calculator()>>> angle = f.protein_folding_angle>>> angle44.33276

Validation:

class Pedometer(object)    ...    @property    def stride_length(self):        return self._stride_length    @stride_length.setter    def stride_length(self, value):        if value > 10:            raise ValueError("This pedometer is based on the human stride - a stride length above 10m is not supported")        else:            self._stride_length = value


One simple use case will be to set a read only instance attribute , as you know leading a variable name with one underscore _x in python usually mean it's private (internal use) but sometimes we want to be able to read the instance attribute and not to write it so we can use property for this:

>>> class C(object):        def __init__(self, x):            self._x = x        @property        def x(self):            return self._x>>> c = C(1)>>> c.x1>>> c.x = 2AttributeError        Traceback (most recent call last)AttributeError: can't set attribute


Take a look at this article for a very practical use. In short, it explains how in Python you can usually ditch explicit getter/setter method, since if you come to need them at some stage you can use property for a seamless implementation.