我現在得到了一個 python 代碼(非常感謝 scotty3785):
from dataclasses import dataclass
@dataclass
class House:
Address: str
Bedrooms: int
Bathrooms: int
Garage: bool
Price: float
def getPrice(self):
print(self.Price)
def newPrice(self, newPrice):
self.Price = newPrice
def __str__(self):
if self.Garage==1:
x="Attached garage"
else:
x="No garage"
return f"""{self.Address}
Bedrooms: {self.Bedrooms} Bathrooms: {self.Bathrooms}
{x}
Price: {self.Price}"""
h1 = House("1313 Mockingbird Lane", 3, 2.5, True, 300000)
h2 = House("0001 Cemetery Lane", 4, 1.75, False, 400000)
print(h1)
print(h2)
h1.newPrice(500000)
h1.getPrice()
h2<h1
現在我需要比較 h1 和 h2 的價格,h2<h1并給出一個布林值作為輸出。
uj5u.com熱心網友回復:
您可以__lt__在您的類上實作特殊方法,也可以將order和eq引數傳遞True給dataclass裝飾器(請注意,它會將您的元素作為元組進行比較)。所以你應該有這樣的東西:
@dataclass(eq=True, order=True)
class House:
Address: str
Bedrooms: int
Bathrooms: int
Garage: bool
Price: float
# your code...
或者,最適合您的情況:
@dataclass(order=True)
class House:
Address: str
Bedrooms: int
Bathrooms: int
Garage: bool
Price: float
def __lt__(self, other_house):
return self.Price < other_house.Price
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/373225.html
上一篇:檢測意外屬性
