Set subtraction in Python

In my Python code, I have this class:

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

    def __repr__(self):
        return 'point: (' + str(self.x) + ', ' + str(self.y) + ')' 

And there are two lists: initialPointsListand burnedPointsList:

initialPointsList = []
initialPointsList.append(_Point2D(1, 1))
initialPointsList.append(_Point2D(1, 2))
initialPointsList.append(_Point2D(1, 3))
initialPointsList.append(_Point2D(1, 4))
initialPointsList.append(_Point2D(1, 5))
initialPointsList.append(_Point2D(1, 6))
initialPointsList.append(_Point2D(1, 7))

burnedPointsList = []
burnedPointsList.append(_Point2D(1, 2))
burnedPointsList.append(_Point2D(1, 3))

I want to calculate the difference between initialPointsListandburnedPointsList

I performed:

result = set(initialPointsList) - set(burnedPointsList)
for item in result:
    print item

And get the following result:

point: (1, 1)
point: (1, 4)
point: (1, 5)
point: (1, 6)
point: (1, 2)
point: (1, 3)
point: (1, 7)

But I expected another result without the coordinates of the burned point:

point: (1, 1)
point: (1, 4)
point: (1, 5)
point: (1, 6)
point: (1, 7)

What is the best way to do this in Python? What doesn't match my code?

+4
source share
2 answers

If you want this to work properly, you need to define __eq__()and __hash__()special techniques. If you define __eq__(), it is usually also useful to define __ne__().

__eq__() True, ( x y ). __ne__() . , __eq__() false, "" , self.

__hash__() . , __eq__(), , , . :

def __hash__(self):
    return hash((self.x, self.y))

- . , XOR (.. self.x ^ self.y) , . , , (, , self.x == self.y).

, , , . self.x self.y .

+6

__eq__, __ne__ __hash__, .

def __eq__(self, other):
    return type(self) is type(other) and self.x == other.x and self.y == other.y

def __ne__(self, other):
    return not self.__eq__(other)

def __hash__(self):
    return hash((self.x, self.y))

, :

point: (1, 5)
point: (1, 6)
point: (1, 1)
point: (1, 4)
point: (1, 7)
+2

Source: https://habr.com/ru/post/1610268/


All Articles