Automatically generating arithmetic operations for a subclass
Arnaud Delobelle
arnodel at googlemail.com
Tue Apr 14 06:20:52 EDT 2009
Arnaud Delobelle <arnodel at googlemail.com> writes:
> binops = ['add', 'sub', 'mul', 'div', 'radd', 'rsub'] # etc
> unops = ['neg', 'abs', invert'] # etc
Oops. There's a missing quote above. It should have been, of course:
unops = ['neg', 'abs', 'invert'] # etc
>
> binop_meth = """
> def __%s__(self, other):
> return type(self)(int.__%s__(self, other))
> """
>
> unop_meth = """
> def __%s__(self):
> return type(self)(int.__%s__(self))
> """
>
> class MyInt(int):
> for op in binops:
> exec binop_meth % (op, op)
> for op in unops:
> exec unop_meth % (op, op)
> del op
>
> HTH
More information about the Python-list
mailing list