[Road to intermediate Python] Enables comparison operations with original classes

Link to summary

https://qiita.com/ganariya/items/fb3f38c2f4a35d1ee2e8

Introduction

In order to study Python, I copied a swarm intelligence library called acopy.

In acopy, many interesting Python grammars and idioms are used, and it is summarized that it is convenient among them.

This time, we will enable comparison operations on instances of the class.

Comparison operation

Comparison operations are defined in Python's built-in data types.

For example, of course, the numbers of instances of the int class can be sorted and compared.

'''
[-2, -1, 1, 2, 3, 5]
'''
a = [1, 2, 3, 5, -1, -2]
a.sort()
print(a)

As mentioned above, you can sort, and of course you can use operators such as " <= ".

Own class

However, you cannot perform comparison operations on your own class. Special attribute methods required to perform comparison operations

Is not defined.

Therefore, you can compare and sort class instances by defining these attributes yourself.

Try to implement

import functools


@functools.total_ordering
class A:

    def __init__(self, x):
        self.x = x

    def __repr__(self):
        return f"x = {self.x}"

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

    def __lt__(self, other):
        return self.x < other.x


'''
[x = 2, x = 3, x = 10, x = 20]
'''
arr = [A(10), A(20), A(3), A(2)]
arr.sort()
print(arr)

Class A has a __repr__ attribute defined to make the print easier to read.

Here, __eq__ and __lt__ are defined, which represent the comparison relationship with other instances ʻother. self.x <other.x of lt` returns True if it is smaller than the opponent, and there is no need to exchange any more! It has become an image.

Actually, only __eq__ and __lt__ are defined in the above class, but they work fine. This is because functools' total_ordering decorator can be used to infer other comparison methods.

Summary

It is convenient to sort and, of course, if statements, etc., if you can perform comparison operations directly on the class. I found it convenient to be able to compare by defining only __eq__ and __lt__. C ++ is so annoying ...

References

-[Python] Allow comparison operations with your own class

Recommended Posts

[Road to intermediate Python] Enables comparison operations with original classes
A road to intermediate Python
[Road to Intermediate] Understanding Python Properties
[Road to Python Intermediate] Call a class instance like a function with __call__
[Road to intermediate Python] Use ternary operators
[Road to intermediate Python] Use lambda expressions
The road to compiling to Python 3 with Thrift
[Road to intermediate Python] Article link summary
[Road to Intermediate] Python seems to be all objects
[Road to Python Intermediate] Define __getattr__ function in class
[Road to intermediate Python] Define in in your own class
[Python] Road to a snake charmer (5) Play with Matplotlib
Connect to BigQuery with Python
Connect to Wikipedia with Python
Post to slack with Python 3
[Road to intermediate Python] Use if statement in list comprehension
I want to automatically attend online classes with Python + Selenium!
Switch python to 2.7 with alternatives
Write to csv with Python
[Road to Python intermediate] Dynamically specify execution method by variable name
Python: How to use async with
Link to get started with python
[Python] Write to csv file with Python
Create folders from '01' to '12' with python
Nice to meet you with python
Try to operate Facebook with Python
Output to csv file with Python
Convert list to DataFrame with python
MP3 to WAV conversion with Python
[Python] Road to snake charmer (3) Python class
To do tail recursion with Python2
Road to Linux Intermediate: Network Edition
What to do with PYTHON release?
Unable to install Python with pyenv
How to use FTP with Python
How to calculate date with python
Easily post to twitter with Python 3
I want to debug with Python
Automate keyboard and mouse operations with python to streamline daily work [RPA]
Try logging in to qiita with Python
Change Python 64bit environment to 32bit environment with Anaconda
English speech recognition with python [speech to text]
Convert memo at once with Python 2to3
HTML email with image to send with python
Memo to ask for KPI with python
Python to remember only with hello, worlds
Output color characters to pretty with python
Bind methods to Python classes and instances
Introduction to Python Image Inflating Image inflating with ImageDataGenerator
Convert Excel data to JSON with python
[Python] Road to snake charmer (1) Environment construction
Convert Hiragana to Romaji with Python (Beta)
Fractal to make and play with Python
I wanted to solve ABC160 with Python
Connect to MySQL with Python within Docker
How to work with BigQuery in Python
Playing card class in Python (with comparison)
[Introduction to Python] Let's use foreach with Python
Single pixel camera to experience with Python
[Python] Introduction to CNN with Pytorch MNIST
Convert FX 1-minute data to 5-minute data with Python