0
0
Pythonprogramming~20 mins

Comparison magic methods in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Comparison Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of custom __eq__ method
What is the output of this code?
Python
class Box:
    def __init__(self, volume):
        self.volume = volume
    def __eq__(self, other):
        return self.volume == other.volume

b1 = Box(10)
b2 = Box(10)
b3 = Box(5)

print(b1 == b2)
print(b1 == b3)
AFalse\nTrue
BFalse\nFalse
CTrue\nTrue
DTrue\nFalse
Attempts:
2 left
💡 Hint
The __eq__ method compares the volume attribute of two Box objects.
Predict Output
intermediate
2:00remaining
Output of __lt__ and __gt__ methods
What is the output of this code?
Python
class Number:
    def __init__(self, value):
        self.value = value
    def __lt__(self, other):
        return self.value < other.value
    def __gt__(self, other):
        return self.value > other.value

n1 = Number(3)
n2 = Number(5)
print(n1 < n2)
print(n1 > n2)
ATrue\nFalse
BFalse\nFalse
CTrue\nTrue
DFalse\nTrue
Attempts:
2 left
💡 Hint
The __lt__ method checks if one value is less than the other, __gt__ checks if greater.
Predict Output
advanced
2:00remaining
Output of __le__ and __ge__ with inheritance
What is the output of this code?
Python
class Base:
    def __init__(self, x):
        self.x = x
    def __le__(self, other):
        return self.x <= other.x
    def __ge__(self, other):
        return self.x >= other.x

class Derived(Base):
    pass

b = Base(7)
d = Derived(7)
print(b <= d)
print(b >= d)
ATrue\nTrue
BFalse\nTrue
CTrue\nFalse
DFalse\nFalse
Attempts:
2 left
💡 Hint
Derived inherits comparison methods from Base and both have the same x value.
Predict Output
advanced
2:00remaining
Output of __eq__ with different types
What is the output of this code?
Python
class Item:
    def __init__(self, id):
        self.id = id
    def __eq__(self, other):
        if not isinstance(other, Item):
            return False
        return self.id == other.id

item = Item(10)
print(item == 10)
print(item == Item(10))
ATrue\nTrue
BFalse\nFalse
CFalse\nTrue
DTrue\nFalse
Attempts:
2 left
💡 Hint
The __eq__ method returns False if the other object is not an Item instance.
Predict Output
expert
3:00remaining
Output of chained comparisons with custom __lt__
What is the output of this code?
Python
class Weird:
    def __init__(self, val):
        self.val = val
    def __lt__(self, other):
        print(f"Comparing {self.val} < {other.val}")
        return self.val < other.val

w1 = Weird(1)
w2 = Weird(2)
w3 = Weird(3)
print(w1 < w2 < w3)
AComparing 1 < 2\nComparing 2 < 3\nFalse
BComparing 1 < 2\nComparing 2 < 3\nTrue
CComparing 1 < 2\nTrue
DComparing 1 < 2\nComparing 3 < 2\nTrue
Attempts:
2 left
💡 Hint
Python evaluates chained comparisons by checking each pair separately.