在 python 中覆盖 _add_ 和 _radd_ 时出错
Error when overriding _add_ and _radd_ in python
当我尝试像这样覆盖 _add_ 和 _radd_ 时:
class adding():
def __init__(self, a):
self.a=a
def _add_(self,x):
self.a += x
def _radd_(self,x):
self.a += x
当我尝试以下操作时出现错误:
adding(1) + 1
TypeError: unsupported operand type(s) for +: 'adding' and 'int'
有人知道我错在哪里吗?
我想用 + x
更新 self.a 值
编辑:
def _add_(self,x):
return adding(self.a + x)
def _radd_(self,x):
return adding(self.a + x)
抛出同样的错误。
To overload the +
sign, we will need to implement __add__()
function in the class. With great power comes great responsibility. We
can do whatever we like, inside this function. But it is sensible to
return a Point object of the coordinate sum.
您必须使用 __add__
:
def __add__(self,x):
当我尝试像这样覆盖 _add_ 和 _radd_ 时:
class adding():
def __init__(self, a):
self.a=a
def _add_(self,x):
self.a += x
def _radd_(self,x):
self.a += x
当我尝试以下操作时出现错误:
adding(1) + 1
TypeError: unsupported operand type(s) for +: 'adding' and 'int'
有人知道我错在哪里吗?
我想用 + x
更新 self.a 值编辑:
def _add_(self,x):
return adding(self.a + x)
def _radd_(self,x):
return adding(self.a + x)
抛出同样的错误。
To overload the
+
sign, we will need to implement__add__()
function in the class. With great power comes great responsibility. We can do whatever we like, inside this function. But it is sensible to return a Point object of the coordinate sum.
您必须使用 __add__
:
def __add__(self,x):