I have the following code, which is making me scratch my head -
class Element:
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
def eq(self, other):
print('comparing {} to {} ({})'.format(self.name,
other.name,
self.name == other.name))
return self.name == other.name
Element.__eq__ = eq
elements = [
Element('a'),
Element('b'),
Element('c'),
Element('d')
]
print('before {}'.format(elements))
elements.remove(elements[3])
print('after {}'.format(elements))
Which yields the following output -
before [a, b, c, d]
comparing a to d (False)
comparing b to d (False)
comparing c to d (False)
after [a, b, c]
Why isn't eq()
outputting comparing d to d (True)
?
The reason I'm monkey patching __eq__
instead of simply implementing it in my Element
class is because I'm testing how monkey patching works before I implement it with one of the libraries I'm using.
Python automatically calls the __eq__ method of a class when you use the == operator to compare the instances of the class.
Python String comparison can be performed using equality (==) and comparison (<, >, != , <=, >=) operators. There are no special methods to compare two strings.
The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and != , except when you're comparing to None .
other is nothing but an argument name. You can call it whatever you want, although methods obey some conventions to make the code clearer. Here are some argument names that usually have a special meaning. self : an argument expected to be the instance from which the method was called.
The fourth element is the exactly same object with the object the code is passing (elements[3]
).
In other word,
>>> elements[3] is elements[3]
True
>>> elements[3] == elements[3]
True
So, no need to check the equality because they(?) are identical (same) one.
Equality check will happen if they are not identical. For example, __eq__
will be called if the code passes another object with the same value:
elements.remove(Element('d'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With