Dynamic Operator Overloading on dict classes in Python

Posted by Ishpeck on Stack Overflow See other posts from Stack Overflow or by Ishpeck
Published on 2010-04-22T21:23:52Z Indexed on 2010/04/22 22:43 UTC
Read the original article Hit count: 249

I have a class that dynamically overloads basic arithmetic operators like so...

import operator

class IshyNum:
    def __init__(self, n):
        self.num=n
        self.buildArith()

    def arithmetic(self, other, o):
        return o(self.num, other)

    def buildArith(self):
        map(lambda o: setattr(self, "__%s__"%o,lambda f: self.arithmetic(f, getattr(operator, o))), ["add", "sub", "mul", "div"])

if __name__=="__main__":
    number=IshyNum(5)
    print number+5
    print number/2
    print number*3
    print number-3

But if I change the class to inherit from the dictionary (class IshyNum(dict):) it doesn't work. I need to explicitly def __add__(self, other) or whatever in order for this to work. Why?

© Stack Overflow or respective owner

Related posts about python

Related posts about dictionary