gpt4 book ai didi

python - 当 'b' 是我的类(class)时,覆盖 a-b 的 __sub__

转载 作者:行者123 更新时间:2023-11-30 23:15:18 25 4
gpt4 key购买 nike

我有课foo这本质上是一个附加了一些额外属性的 float 。我可以覆盖它的__sub__方法,以便我可以在一个方向上进行减法,但我不知道如何以另一种方式进行减法:

class foo():
def __init__(self, value, otherstuff):
self.value = value
self.otherstuff = otherstuff

def __sub__(self, other):
return self.value - other

a = 5
b = foo(12, 'blue')
print b-a # this works fine and returns 7
print a-b # I want this to return -7 but it obviously doesn't work

有办法做到这一点吗?

add、sub、mul、div 的通用解决方案是理想的,但 sub 和 div 是最紧迫的,因为它们是不可逆的。

最佳答案

您只需要重写__rsub__,即可进行右侧减法:

class foo():
def __init__(self, value, otherstuff):
self.value = value
self.otherstuff = otherstuff

def __sub__(self, other):
return self.value - other

def __rsub__(self, other):
return other - self.value

输出:

print(b - a)
7

print(a - b)
-7

还有类似的方法,如__radd____rmul__用于其他操作。

关于python - 当 'b' 是我的类(class)时,覆盖 a-b 的 __sub__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28289417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com