gpt4 book ai didi

python - 比较python类中的变量

转载 作者:太空宇宙 更新时间:2023-11-04 10:32:58 25 4
gpt4 key购买 nike

我正在尝试编写一个方法(it),将矩形的大小(面积)与作为参数传递的另一个矩形的面积进行比较:

class Rectangle:
def __init__(self, x, y):
self.width = x
self.height = y

def area(self):
a = self.width * self.height
return a

def __it__(self,second):
return self.area < second.area

但我不断收到错误:

TypeError: unorderable types: Rectangle() < Rectangle()

我不确定如何解决这个问题

最佳答案

你打错了。它是 __lt__,而不是 __it__,您需要将 area() 作为函数调用,除非您将其设置为 property。 .

修复所有这些......

>>> class Rectangle:
... def __init__(self, x, y):
... self.width = x
... self.height = y
... def area(self):
... a = self.width * self.height
... return a
... def __lt__(self,second):
... return self.area() < second.area()
...
>>> Rectangle(1,3) > Rectangle(4,5)
False

关于python - 比较python类中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25180559/

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