https://qiita.com/ganariya/items/fb3f38c2f4a35d1ee2e8
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 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 " <=
".
However, you cannot perform comparison operations on your own class. Special attribute methods required to perform comparison operations
__lt__
less than__le__
less or equal__eq__
equal__ne__
not equal__gt__
greater than__ge__
greater or equalIs not defined.
Therefore, you can compare and sort class instances by defining these attributes yourself.
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.
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 ...
-[Python] Allow comparison operations with your own class
Recommended Posts