如何为Python自定义类实现<运算符以比较实例的Price属性值
实现方法
你需要为House类重载<运算符对应的魔术方法__lt__,逻辑为对比两个实例的Price属性值即可,同时如果要直接看到比较结果,需要把h2<h1放在print()中输出。
修改后的完整代码如下:
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 __lt__(self, other): # 仅对比两个实例的Price属性返回布尔结果 return self.Price < other.Price 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() # 打印比较结果 print(h2 < h1)
运行后最后一行输出为True,符合预期:h2的Price为400000,h1修改后Price为500000,400000<500000返回布尔值True。
如果你需要支持其他比较运算符,可以参考同样的逻辑重载对应的魔术方法:
>对应__gt__<=对应__le__>=对应__ge__==对应__eq__
内容的提问来源于stack exchange,提问作者Hayyan Yousuf Khan
相关产品推荐
相关产品推荐

