我正在尝试使用下面的代码动态设置方法来模拟数字对象。但相反,每个方法都设置为循环中的最后一个。为什么会发生这种情况,我该如何说服 Python 使用 DWIM?
#!/usr/bin/env python3.5
class Foo(float):
pass
for tp in ("add", "sub", "mul", "truediv", "floordiv", "mod", "divmod", "pow"):
methname = "__{:s}__".format(tp)
print("defining", methname)
def func(self, other):
x = getattr(super(Foo, self), methname)(other)
print("I calculated x={:.3f}!".format(x))
return x
func.__name__ = methname
setattr(Foo, methname, func)
if __name__ == "__main__": # test
print("Addition", Foo(3) + Foo(3))
print("Multiplication", Foo(3) * Foo(3))
$ ./dyn.py
defining __add__
defining __sub__
defining __mul__
defining __truediv__
defining __floordiv__
defining __mod__
defining __divmod__
defining __pow__
I calculated x=27.000!
Addition 27.0
I calculated x=27.000!
Multiplication 27.0