python class类里面直接运行代码,如何在您自己的类上重写或执行python中的min/max?...

本文探讨如何使用Python类实现自定义比较操作符`__gt__`和`__lt__`,以实现类似`max(a, b)`的功能。通过创建`MyClass`,作者展示了如何比较两个实例的属性`item1`和`item2`来确定它们的相对大小。然而,代码在实例`a`和`b`的比较中返回了错误的结果。问题在于`__gt__`和`__lt__`方法的实现可能不完全正确,导致了预期之外的行为。
摘要由CSDN通过智能技术生成

不确定这个问题的最佳标题,但我如何重写或执行

min(a, b)

max(a, b)

关于我做的类的东西?我可以超越

gt

max(a, b, c ,d)

. 这个类也将有多个属性,但是我认为这个例子中的2就足够了。

class MyClass:

def __init__(self, item1, item2):

self.item1 = item1

self.item2 = item2

def __gt__(self, other):

if isinstance(other, MyClass):

if self.item1 > other.item1:

return True

elif self.item1 <= other.item1:

return False

elif self.item2 > other.item2:

return True

elif self.item2 <= other.item2:

return False

def __lt__(self, other):

if isinstance(other, MyClass):

if self.item1 < other.item1:

return True

elif self.item1 >= other.item1:

return False

elif self.item2 < other.item2:

return True

elif self.item2 >= other.item2:

return False

前任:

a = MyClass(2,3)

b = MyClass(3,3)

print(a > b)

# False

我试图超越

__cmp__

希望能够做到

最大值(a,b)

然后回来

b

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值