如何在Python类中实现优雅的相等比较?
在 Python 类中支持相等(“等价”)的优雅方法
在面向对象编程中,定义自定义类的对象之间的相等检查通常至关重要。 Python 通过实现特殊方法 eq 和 __ne__ 来实现这一点,分别用于等价和不等式比较。
一种既定方法是比较 dict 属性两个对象:
class Foo: def __init__(self, item): self.item = item def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False
但是,请考虑以下更简单的方法:
class Number: def __init__(self, number): self.number = number def __eq__(self, other): return isinstance(other, Number) and self.number == other.number
这种简洁的方法消除了复杂的 dict 比较的需要,使其成为一种优雅的方法
此外,它无缝地处理子类化,确保可交换且一致的等式检查:
class SubNumber(Number): pass n1 = Number(1) n2 = Number(1) n3 = SubNumber(1) n4 = SubNumber(4) print(n1 == n2) # True print(n2 == n1) # True print(n1 == n3) # True print(n1 != n4) # True print(len(set([n1, n2, n3]))) # 1
要完成解决方案,必须重写 hash 方法一致的哈希和唯一标识:
class Number: def __init__(self, number): self.number = number def __eq__(self, other): return isinstance(other, Number) and self.number == other.number def __hash__(self): return hash(self.number)
这解决了使用 dict 进行相等比较时遇到的哈希问题,确保可靠的集合行为和不同对象的唯一标识。
以上是如何在Python类中实现优雅的相等比较?的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...

Python3.6环境下加载pickle文件报错:ModuleNotFoundError:Nomodulenamed...

使用Scapy爬虫时管道文件无法写入的原因探讨在学习和使用Scapy爬虫进行数据持久化存储时,可能会遇到管道文�...
