为了float
使用包装器对多个数字操作进行子类化和覆盖,我查看了这个示例并尝试了以下操作:
def naturalize(*methods):
def decorate(cls):
for method in methods:
method = '__' + method + '__'
original = getattr(cls.__base__, method)
setattr(cls, method, lambda self, *args, **kwargs: cls(original(self, *args, **kwargs)))
return cls
return decorate
@naturalize('add', 'sub', 'mul')
class P(float):
pass
print('Test result:', P(.1) + .2, P(.1) - .2, P(.1) * .2)
# Test result: 0.020000000000000004 0.020000000000000004 0.020000000000000004
这不起作用:__add__
,__sub__
并且__mul__
都像__mul__
. 因此,我查看了另一个示例并尝试了:
def naturalize(*methods):
def decorate(cls):
def native(method):
original = getattr(cls.__base__, method)
return lambda self, *args, **kwargs: cls(original(self, *args, **kwargs))
for method in methods:
method = '__' + method + '__'
setattr(cls, method, native(method))
return cls
return decorate
@naturalize('add', 'sub', 'mul')
class P(float):
pass
print('Test result:', P(.1) + .2, P(.1) - .2, P(.1) * .2)
#Test result: 0.30000000000000004 -0.1 0.020000000000000004
现在,这确实奏效了。但我仍然不确定我的第一种方法到底出了什么问题。任何人都可以向我解释一下到底是怎么回事__add__
,__sub__
最终__mul__
都像这样工作__mul__
吗?