比较两个不同 class 对象的整数值
Compare integer values of two different class objects
我现在得到一个 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 的价格,并给出一个布尔值作为输出。
您可以在 class 上实现特殊方法 __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
我现在得到一个 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 的价格,并给出一个布尔值作为输出。
您可以在 class 上实现特殊方法 __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