我现在得到了一个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
现在我需要使用h2<h1
来比较h1和h2的价格,并给出一个布尔值作为输出。
您可以在类上实现特殊方法__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