【发布时间】:2010-04-22 21:23:52
【问题描述】:
我有一个类可以像这样动态重载基本算术运算符...
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
但是,如果我将类更改为从字典 (class IshyNum(dict):) 继承,则它不起作用。我需要明确地def __add__(self, other) 或其他任何东西才能使它工作。为什么?
【问题讨论】:
标签: python dictionary operator-overloading