允许自定义 python class 双向添加
Allow a custom python class to add in both directions
我创建了一个自定义 class,我希望它能够以两种方式处理加法。截至目前,只有当我在右侧有 class 并且在左侧有要添加的东西(即 class+ 变量)时,它才有效。如何更改下面的代码以包括相反方向的加法(即另一个变量+class)。
def __add__(self,other):
return self.offset+other
使用radd()特殊功能:
def __radd__(self,other):
return self.offset + other
如果左操作数不支持加法运算且操作数类型不同,将调用此函数
我创建了一个自定义 class,我希望它能够以两种方式处理加法。截至目前,只有当我在右侧有 class 并且在左侧有要添加的东西(即 class+ 变量)时,它才有效。如何更改下面的代码以包括相反方向的加法(即另一个变量+class)。
def __add__(self,other):
return self.offset+other
使用radd()特殊功能:
def __radd__(self,other):
return self.offset + other
如果左操作数不支持加法运算且操作数类型不同,将调用此函数