运算符重载
__add__ 和 _radd_
class Node:
def __init__(self, num):
self.n = num
def __add__(self, other):
if isinstance(other, Node):
t = self.n + other.n
else:
t = self.n + other
return t
__radd__ = __add__
上面代码通过自定义__add__
来实现Node对象的加法操作。
其中__radd__
是为了解决4 + Node
的情况,首先尝试(4).__add__(Node)
,返回NotImplemented
之后,会检查是否定义了__radd__
,如果定义了就尝试Node.__radd__(4)
。
__truediv__ 和__floordiv__
class Node:
def __init__(self, num):
self.n = num
def __truediv__(self, other): # for /
if isinstance(other, Node):
t = self.n / other.n
else:
t = self.n / other
return t
def __floordiv__(self, other): # for //
if isinstance(other, Node):
t = self.n // other.n
else:
t = self.n // other
return t
Donate me.
- Post link: https://sanzo.top/Default/python/
- Copyright Notice: All articles in this blog are licensed under unless otherwise stated.