有没有一种方法可以检查两个对象在python中每个变量中是否包含相同的值? [英] Is there a way to check if two object contain the same values in each of their variables in python?
本文介绍了有没有一种方法可以检查两个对象在python中每个变量中是否包含相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何检查a的两个实例
class FooBar(object):
__init__(self, param):
self.param = param
self.param_2 = self.function_2(param)
self.param_3 = self.function_3()
一样吗?相同是指它们所有变量的值都相同.
are identical? By identical I mean they have the same values in all of their variables.
a = FooBar(param)
b = FooBar(param)
我想到了
if a == b:
print "a and b are identical"!
这样做会没有副作用吗?
Will this do it without side effects?
我的问题的背景是单元测试.我想实现以下目标:
The background for my question is unit testing. I want to achieve something like:
self.failUnlessEqual(self.my_object.a_function(), another_object)
推荐答案
如果您希望==
工作,请在您的类中实现__eq__
方法以执行丰富的比较.
If you want the ==
to work, then implement the __eq__
method in your class to perform the rich comparison.
如果您只想比较 all 属性的相等性,则可以通过比较每个对象中的__dict__
来简洁地做到这一点:
If all you want to do is compare the equality of all attributes, you can do that succinctly by comparison of __dict__
in each object:
class MyClass:
def __eq__(self, other) :
return self.__dict__ == other.__dict__
这篇关于有没有一种方法可以检查两个对象在python中每个变量中是否包含相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文