Operator overloading

Terry Reedy tjreedy at udel.edu
Sat Jan 26 22:34:47 EST 2008


| > > Sure. Cosines are a monadic operation and the monadic '+' is a NOP, 
so
| > > why shouldn't I define +45 to return cosine of 45, (presuming I 
needed
| > > lots of cosines). I'd even let you define your own operators. Lots of
| > > programmers really liked '++' and '--', for examples.

One cannot change builtin types.  One can subclass most of them and 
override most if not all the special methods.

import math as m
class trigint(int):
    def __pos__(self):
        return m.cos(m.pi*self/180.0)

print +trigint(45)
>>>
0.707106781187

Of course, for this case,
def cosi(degrees): return m.pi*degrees/180.0
would probably be more sensible.

There is and is no prospect of being able to add operators.

Terry Jan Reedy






More information about the Python-list mailing list