Make it possible to use the equivalence judgment defined by yourself after knowing the mechanism of equivalence judgment of objects in python.
About the judgment mechanism with ʻobj1 == obj2 and ʻobj1! = obj2
python : 3.5.1, 2.7.10
class Foo(object):
def __init__(self, name, age):
self.name = name
self.age = age
As mentioned above, after defining the Foo class, create instances of foo1 and foo2 as shown below, If the same value is judged or the existence of the list is judged, it will be True for the same instance, but if the member variable values are the same but the instances are different, it will be False.
foo1 = Foo("foo", 24)
foo2 = Foo("foo", 24)
print(foo1 == foo1) # -> True
print(foo1 == foo2) # -> False
print(foo1 in [ foo1 ]) # -> True
print(foo1 in [ foo2 ]) # -> False
print(foo1 != foo1) # -> False
print(foo1 != foo2) #-> True
When performing equivalence judgment with ==
or ʻobj in objlist of python, ʻObj.__eq__
method is called
On the other hand, ʻobj.neis called for
! = However, if you define ʻobj.__eq__
, in 3.5.1 (all 3 series?), ʻobj.ne returns the opposite, so you only need to override ʻobj.__eq__
.
In 2.7.10, if you don't define __ne__
as well, the result of ʻobj.ne will not return the opposite value of the overridden ʻobj.__eq__
.
If you want to unify the 2nd and 3rd systems, it is recommended to define __ne__
.
However, note that in the case of __eq__
, you must first call the method ʻis instance (obj, CLASSNAME)that determines whether the comparison target is the same class. If the member variables
name and ʻage
are the same, if they are considered to be the same, define as follows
class Bar(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, obj):
if isinstance(obj, Bar):
return self.name == obj.name and self.age == obj.age
else:
return False
def __ne__(self, obj):
return not self.__eq__(obj)
If you define the Bar class as above, create instances of bar1, bar2, bar3 as follows and see the result of equivalence judgment etc., it will be as follows.
bar1 = Bar("bar", 24)
bar2 = Bar("bar", 24)
bar3 = Bar("foo", 24)
print(bar1 == bar1) # -> True
print(bar1 == bar2) # -> True
print(bar1 == bar3) # -> False
print(bar1 in [ bar1 ]) # -> True
print(bar2 in [ bar1 ]) # -> True
print(bar3 in [ bar1 ]) # -> False
print(bar1 != bar1) # -> False
print (bar1! = bar2) #-> False 2.7.10 will be True if ne is not defined print(bar1 != bar3) # -> True
Recommended Posts