首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何对python中的对象执行深度查询

如何对python中的对象执行深度查询
EN

Stack Overflow用户
提问于 2014-03-11 17:53:45
回答 3查看 4.8K关注 0票数 2

有什么函数可以让我

代码语言:javascript
复制
class Test():
    def __init__(self):
        self.value_1 = 42

x = Test()
y = Test()
deepequals(x, y) == True
x.value = 7
deepequals(x, y) == False
y.value = 7
deepequals(x, y) == True

但是,默认情况下,它总是错误的,因为x和y是不同的Test实例

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-03-11 18:01:20

您可以实现__eq__ (等于)“魔术方法”:

代码语言:javascript
复制
class Test():
    def __init__(self):
        self.value_1 = 42
    def __eq__(self, other):
        return self.__dict__ == other.__dict__

其中__dict__保存了所有实例属性。当两个对象对所有相同的属性都有相同的值时,这将返回True。这给出了您想要的结果:

代码语言:javascript
复制
>>> x = Test()
>>> y = Test()
>>> x == y
True
>>> x.value = 7
>>> x == y
False
>>> y.value = 7
>>> x == y
True

若要支持与没有__dict__属性的对象(如C中定义的对象或使用__slots__ )的比较,可以首先使用hasattr检查该属性

代码语言:javascript
复制
return hasattr(other, '__dict__') and self.__dict__ == other.__dict__

或者使用默认的getattr安全地访问它:

代码语言:javascript
复制
return self.__dict__ == getattr(other, '__dict__', None)
票数 1
EN

Stack Overflow用户

发布于 2020-09-20 11:19:50

代码语言:javascript
复制
class Test:
    def __init__(self):
        self.value_1 = 42
        
    def __eq__(self, other):
        return (
             self.__class__ == other.__class__ and
             self.value_1 == other.value_1)

t1 = Test()
t2 = Test()
print(t1 == t2)

输出

代码语言:javascript
复制
True
票数 1
EN

Stack Overflow用户

发布于 2014-03-11 18:02:41

您可能希望实现类的__eq__。然后可以使用标准比较运算符:

代码语言:javascript
复制
class Test():
    def __init__(self):
        self.value = 42

    def __eq__ (self, other):
        return self.value == other.value

x = Test()
y = Test()
print (x == y)
x.value = 7
print (x == y)
y.value = 7
print (x == y)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22332729

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档