terça-feira, 5 de maio de 2015

Python (2.7 and 3.0) - get/set and operators

Python continue surprising me.

Is possible verify attribute's value using the annotation @ATTR.setter on set method, too you can modify attribute's return using the annotation @property on get method.

 Finalizing this post, is possible with python, override classes' operators like c++.

See the example below. Details in references links.

class Div(object):

    def __init__(self, op, di):
        self.op = op
        self._di = di 
 
    # GET di
    @property
    def di(self):
        return self._di 
 
    # SET di
    @di.setter
    def di(self, value):
        if (value == 0): 
            raise ValueError('Invalid value')
        else:
            self.di = value 
 
    # OPERATOR ADD
    def __add__(a, b): 
        x = Div(0, 0)
        x.op = a.op + b.op
        x._di = a.di + b.di
        return x

    def __str__(self):
        return ("%s/%s") % (self.op, self.di)
    

x = Div(1,3)
y = Div(2,2)

z = x + y 

print(x)
print(y)
print(z)

x.di = 0 
 
Execution's Result:
1/3
2/2
3/5
Traceback (most recent call last):
  File "/tmp/exemplo1.py", line 38, in 
    x.di = 0
  File "/tmp/exemplo1.py", line 15, in di
    raise ValueError('Invalid value')
ValueError: Invalid value

References:

Drunk Penguins

Drunk Penguins
Drunk Penguins