要解决的主要问题是像这样的魔术方法__add__
在类上查找,而不是在对象本身上查找;否则你可以写self.__add__ = a.__add__
in the __init__
方法。为了解决这个问题,我们需要在类上声明方法B
,而不是它的个别实例。
功能delegate
下面定义的工作原理是添加一个方法B
班级。该方法需要self
这将是一个B
实例,因此它必须动态加载a
属性,然后是它的__add__
method.
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
def delegate(cls, attr_name, method_name):
def delegated(self, *vargs, **kwargs):
a = getattr(self, attr_name)
m = getattr(a, method_name)
return m(*vargs, **kwargs)
setattr(cls, method_name, delegated)
delegate(B, 'a', '__add__')
delegate(B, 'a', '__sub__')
Example:
>>> b = B(A())
>>> b + 3
9
>>> b - 4
8