Equivalence of objects in Python

Purpose

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

environment

python : 3.5.1, 2.7.10

Equivalence judgment with python built-in function

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

If you make your own

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 variablesname 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

2.7.10 (probably all 2.7 series) also requires the following

    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

Equivalence of objects in Python
Implementation of quicksort in Python
Pixel manipulation of images in Python
Division of timedelta in Python 2.7 series
MySQL-automatic escape of parameters in python
Handling of JSON files in Python
Assignments and changes in Python objects
Implementation of life game in Python
Waveform display of audio in Python
6 ways to string objects in Python
Examine the object's class in python
Law of large numbers in python
Implementation of original sorting in Python
Reversible scrambling of integers in Python
Quadtree in Python --2
Python in optimization
CURL in python
Conversion of string <-> date (date, datetime) in Python
Geocoding in python
Introduction of Python
SendKeys in Python
Check the behavior of destructor in Python
(Bad) practice of using this in Python
Meta-analysis in Python
Unittest in python
Output tree structure of files in Python
Display a list of alphabets in Python 3
Comparison of Japanese conversion module in Python3
Summary of various for statements in Python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Basics of Python ①
The result of installing python in Anaconda
Basics of python ①
Programming in python
Gang of Four (GoF) Patterns in Python
Plink in Python
Constant in python
Copy of python
The basics of running NoxPlayer in Python
Lifegame in Python.
FizzBuzz in Python
Bulk replacement of strings in Python arrays
Project Euler # 16 "Sum of Powers" in Python
Sqlite in python
StepAIC in Python
Traffic Safety-kun: Recognition of traffic signs in Python
Summary of built-in methods in Python list
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Non-logical operator usage of or in python
In search of the fastest FizzBuzz in Python
Constant in python