It's strange to compare the integer as is. I thought while looking at , is
compares id()
based on what?
Basic types such as integers can just compare values, but I wonder how to compare objects.
python equal
==
returns true/false with the __eq__()
method.
__eq__()
is included in existing types or user-defined classes
Override is also possible.
class foo(object):
def__eq__(self, other): #In this class, instances always return true no matter what they compare
return True
def __init__(self):
self.a = 5
self.b = 4
class bar(object):
def__eq__(self, other): #In this class, instances always return false no matter what they compare
return False
myfoo1 = foo()
myfoo2 = foo()
mybar1 = bar()
print("myfoo1 == myfoo2:\t", myfoo1 == myfoo2)
print("myfoo1 == 3:\t\t", myfoo1 == 3)
print("3 == myfoo1:\t\t", 3 == myfoo1)
print("myfoo1 == mybar1:\t", myfoo1 == mybar1)
print("mybar1 == myfoo1:\t", mybar1 == myfoo1)
Output:
myfoo1 == myfoo2: True
myfoo1 == 3: True
3 == myfoo1: True
myfoo1 == mybar1: True
mybar1 == myfoo1: False
© 2024 OneMinuteCode. All rights reserved.