Comparing two identical objects in Python (2.7) returns False(在 Python (2.7) 中比较两个相同的对象返回 False)
问题描述
我在 Python 中有一个名为 object_from_DB 的函数.定义并不重要,只是它接受一个 ID 值作为参数,使用 sqlite3 库从 .db 文件中的表中提取匹配值,然后使用这些值作为参数对象的初始化.使用此功能不会更改数据库.
I have a function in Python called object_from_DB. The definition isn't important except that it takes an ID value as an argument, uses the sqlite3 library to pull matching values from a table in a .db file, and then uses those values as arguments in the initialization of an object. The database is in no way changed by the use of this function.
鉴于此,这个示例代码让我感到困惑.
This sample code, in light of this, baffles me.
>>> x = object_from_DB(422)
>>> y = object_from_DB(422)
>>> x == y
False
为什么会发生这种情况,什么技术会导致 x 和 y 在比较时返回 True?
Why does this happen, and what sort of technique will cause x and y to return True when compared?
推荐答案
默认情况下,任何用户定义类的两个不同实例都是不相等的:
By default, two distinct instances of any user-defined class are unequal:
>>> class X: pass
...
>>> a = X()
>>> b = X()
>>> a == b
False
如果你想要不同的行为,你必须定义它:
If you want different behaviour, you have to define it:
class Y:
def __init__(self, value):
self.value = value
def __eq__(self, other):
return self.value == other.value
>>> c = Y(3)
>>> d = Y(3)
>>> e = Y(4)
>>> c == d
True
>>> d == e
False
这篇关于在 Python (2.7) 中比较两个相同的对象返回 False的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Python (2.7) 中比较两个相同的对象返回 False
基础教程推荐
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 无法解决整理冲突 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 在 SQL 中连接多个表 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
