You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 11:36:05