class Point: def __init__(self, x, y): self.x = x self.y = y 

How to make that objects of a class were equal provided that coordinates x (or) are equal? In itto should be like this:

 >>> a = Point(1, 2) >>> b = Point(1, 3) >>> c = Point(2, 2) >>> a == b True >>> a == c False 
  • one
    def __eq__(self, other): return other.x == self.x So should it beat? - lalalala
  • why do you make unequal objects equal? Not easier to compare the coordinates? - codename0082016
  • I need equality to be fulfilled with my condition - lalalala
  • @ codename0082016 in the example, he indicated equality only in X - Pavel Durmanov

2 answers 2

Is suitable?

 In [11]: class Example: ...: def __init__(self, x, y): ...: self.x = x ...: self.y = y ...: def __eq__(self, other): ...: if self.x == other.x and self.y == other.y: ...: return True ...: return False In [12]: A = Example(1, 1) In [13]: B = Example(1, 1) In [14]: A == B Out[14]: True In [15]: a = Example(1, 2) In [16]: A == a Out[16]: False 
  • Yes, I was more interested in the syntax and name of the method __eq __ (I did not know it) - lalalala
  • @lalalala if the answer suits you - click the check mark on the left. - Pavel Durmanov
  • Well, the answer code does not give a question, put in the 6th line what I wrote in the comment (maybe someone will also look for an answer to such a question, and the answer is not correct, it only suits me) - lalalala
  • but the answer to the question is incorrect) the answer came up to me but he does not answer the question - lalalala
  • @lalalala What else are you interested in? In my opinion, I gave you the answer, if not - add or reformulate the question. - Pavel Durmanov

To determine the rest of the comparison operations, except for __eq__ , it is convenient to use total_ordering . It is enough to define only one method, for example __lt__ , the rest will total_ordering created by total_ordering

 from functools import total_ordering @total_ordering class Point: def __init__(self, x, y): self.x = x self.y = y def __lt__(self, other): return self.x < other.x or self.y < other.y def __eq__(self, other): return self.x == other.x and self.y == other.y A = Point(1, 1) B = Point(1, 1) C = Point(2, 1) print(A == B, A < B, A >= B, B <= C) # True False True True 

There is also a namedtuple that can do it all.

 from collections import namedtuple point = namedtuple('Point', ['x', 'y']) A = point(1, 1) B = point(1, 1) C = point(2, 1) print(A == B, A < B, A >= B, B <= C) # True False True True