【发布时间】:2020-01-14 22:24:10
【问题描述】:
我有几个类和一个函数:
from functools import partial
def fn(other, self, name):
print(f"calling {name} with {other}")
func = getattr(self.a, name)
return func(other)
class A:
def __add__(self, other):
return 9
def __mul__(self, other):
return 7
def __sub__(self, other):
return 8
class B:
def __init__(self,a):
self.a = a
for name in ['add', 'sub']:
name = f"__{name}__"
p = partial(fn, self=self,name=name)
setattr(self, name, p)
p.__name__ = name
我希望能够使用将魔术方法转发到现有属性。我不想继承这个类,因为我不想要所有的内置函数。只是一对。例如,我可能想使用来自不同类的乘法。我试图避免这样的编码:
def __add__(self, other):
self.a.__add__(other)
使用上面的代码,我收到以下信息:
>>> b = B(A())
>>> b + 3
TypeError Traceback (most recent call last)
<ipython-input-40-fa904b7bb783> in <module>
----> 1 b + 3
2
TypeError: unsupported operand type(s) for +: 'B' and 'int'
>>> b.__add__(3)
calling __add__ with 3
9
也许我遗漏了一些简单的东西,但我找不到动态添加内置函数的方法。
【问题讨论】:
标签: python partial-application