How does Python establish equality between objects?

I found an error in my program in the line where I tested the existence of an object in the list of objects. The line always returned False, which meant that the object was not in the list. In fact, this went on even when I did the following:

class myObject(object): __slots__=('mySlot') def __init__(self,myArgument): self.mySlot=myArgument print(myObject(0)==myObject(0)) # prints False a=0 print(myObject(a)==myObject(a)) # prints False a=myObject(a) print(a==a) # prints True 

I used to use deepcopy, but I'm not experienced enough for Python to know when this is never needed, or mechanically, what is the difference. I also heard about pickling, but never used it. Can someone explain to me what is going on here?

Oh and one more thing. Line

 if x in myIterable: 

probably checking the equality between x and each element in myIterable, right? Therefore, if I can change the perceived equality between two objects, can I change the output of this line? Is there any built-in for this and all other built-in operators?

+4
source share
3 answers
  • It passes the second operand to the __eq__() method of the first.

  • Wrong. It passes the first operand to the __contains__() method of the second or iterates the second execution of equality comparisons if such a method does not exist.

Perhaps you wanted to use is , which compares the identifier instead of equality.

+6
source

The string myObject(0)==myObject(0) in your code creates two different instances of the myObject, and since you did not define __eq__ , they are compared for identification (for example, memory location).

x.__eq__(y) <==> x==y and your line about if x in myIterable: using "peer comparison" for the in keyword is true, unless iterability defines __contains__ .

 print(myObject(0)==myObject(0)) # prints False #because id(left_hand_side_myObject) != id(right_hand_side_myObject) a=0 print(myObject(a)==myObject(a)) # prints False #again because id(left_hand_side_myObject) != id(right_hand_side_myObject) a=myObject(a) print(a==a) # prints True #because id(a) == id(a) 
+1
source

myObject(a) == myObject(a) returns false because you are creating two separate instances of myObject (with the same attribute a). Thus, two objects have the same attributes, but they are different instances of your class, so they are not equal.

If you want to check if the object is in the list, then yes,

 if x in myIterable 

will probably be the easiest way to do this.

If you want to check if an object has the same attributes as another object in the list, maybe try something like this:

 x = myObject(a) for y in myIterable: if x.mySlot == y.mySlot: print("Exists") break 

Or you can use __eq__(self,other) in your class definition to set conditions for quality assurance.

+1
source

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


All Articles