Automatically generating arithmetic operations for a subclass

Diez B. Roggisch deets at nospam.web.de
Tue Apr 14 14:14:11 CEST 2009


andrew cooke wrote:

> Arnaud Delobelle wrote:
>> I do this:
>>
>> binops = ['add', 'sub', 'mul', 'div', 'radd', 'rsub'] # etc
>> 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
> 
> what's the "del" for?

To not pollute the namespace of MyInt - otherwise, you could do

MyInt(10).op


Diez



More information about the Python-list mailing list