[英]Comparing variables within classes in python
我正在嘗試編寫一種方法( 它 ),將矩形的大小(面積)與作為參數傳遞的另一個矩形的面積進行比較:
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
Area是一種方法,您正在使用它,就像它是一個變量一樣。 添加括號可以解決該問題(如果您嘗試執行的操作少於此操作,則應為__lt__
):
def __lt__(self, second):
return self.area() < second.area()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.