Welcome to this challenging Python operator overloading MCQ quiz! In this quiz, we have compiled the top 25 multiple-choice questions based on operator overloading.
These 25 MCQ quizzes will test your knowledge from basic to advanced levels, as well as level up your understanding and knowledge in operator overloading.
Whether you’re a beginner or an experienced Python programmer, this quiz is perfect for interview preparation, competitive exams, and enhancing your knowledge in operator overloading.
So, are you ready to score 25/25? Let’s see how well do you really understand operator overloading concept in Python? Let’s begin with question number 1.👇
- The magic method __add__() provided by Python is used to define the behavior of the addition operator (+).
- This method is called when the + operator is used on instances of a class.
- When the + operator is used between two objects of a class, Python internally calls the __add__() method of the left-hand operand, passing the right-hand operand as an argument.
class A:
def __add__(self, other):
return "Addition done"
a = A()
print(a + a)- Normally, the plus operator (+);/.
- between numbers performs addition.
- Here, a is an object, so Python looks for the method a.__add__(a).
- Since the __add__() defined in the above code, Python calls __add__(self=a, other=a), executes the method body, and returns the string “Addition done”.
- This string is returned as the result of a + a.
class Test:
def __init__(self, x):
self.x = x
def __add__(self, other):
return self.x + other.x
t1 = Test(20)
t2 = Test(30)
result = t1 + t2
print(result)class Test:
def __eq__(self, other):
return True
print(Test() == Test())- The == operator in Python internally calls the special method __eq__.
- In the above class, __eq__() method is overridden to always return True, no matter what objects are compared.
- When Python interpreter execute Test() == Test() is executed, it calls Test().__eq__(Test()) and returns True.
- Therefore, the output is True.
class Test:
def __mul__(self, other):
return "Hello"
t = Test()
print(t * 3)- Normally, the multiplication operator (*) multiplies numbers or repeats strings/lists.
- Since b is an object, Python calls b.__mul__(3).
- The other parameter receives the value 3, but it is not used anywhere.
- Therefore, the method returns only “Hello”.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __pow__(self, exponent):
return Point(self.x ** exponent, self.y ** exponent)
def __str__(self):
return f"Point({self.x}, {self.y})"
p = Point(2, 3)
print(p ** 2)- Python sees the ** operator with a left operand p (an instance of Point) and a right operand 2 (an int).
- It looks for a __pow__ method on the left-hand object (p).
- Since the class Point defines __pow__, Python will call p.__pow__(2) internally.
- Inside the __pow__() method, the parameter self is the original Point object with self.x == 2 and self.y == 3.
- The exponent is the integer 2.
- The self.x ** exponent → 2 ** 2 = 4 and self.y ** exponent → 3 ** 2 = 9.
- The method returns a new Point(4, 9) object.
- The __str__() method formats it as “Point(4, 9)”.
- If the class Point did not define __pow__() method, Python would raise a TypeError.
class Test:
def __radd__(self, other):
return other + 10
t = Test()
print(5 + t)class A:
def __mul__(self, other):
return "Hi"
def __rmul__(self, other):
return "Bye"
print(5 * A())- The expression 3 * A() triggers the reverse multiplication operation because the left operand (3) is an integer (built-in type) that doesn’t know how to multiply with a custom A object.
- Since 3 (an int) doesn’t support multiplication with a custom object A, Python calls A.__rmul__(self, 3) and returns “Bye”.
- If __rmul__() method didn’t exist, Python would raise a TypeError.
- The __mul__() method is called for A() * 3, while the __rmul__() is called for 3 * A() when the left operand doesn’t support the operation.
class Number:
def __pow__(self, exponent):
return exponent - 1
n = Number()
print(n ** 3)class Test:
def __sub__(self, other):
return "Left Sub"
def __rsub__(self, other):
return "Right Sub"
print(Test() - 2)
print(2 - Test())class Number:
def __eq__(self, other):
return self.value == other.value
n1 = Number()
n1.value = 10
n2 = Number()
print(n1 == n2)- The code will raise an AttributeError because n1 has n1.value = 10, but n2 does not have a .value attribute defined.
- When n1 == n2 executes, Python calls Number.__eq__(n1, n2), which tries to access other.value.
- Since n2.value doesn’t exist, Python raises an AttributeError.
class X:
def __eq__(self, other):
return True
x1 = X()
x2 = X()
print(x1 == x2, x1 != x2)- When Python interpreter executes x1 == x2, the == operator calls the special method __eq__().
- Since the __eq__() always returns True, no matter what other is.
- So, x1 == x2 results True.
- When Python executes x1 != x2, the != operator calls __ne__ (not equal) if it is defined.
- Since the __ne__() is not defined in the class, Python will try to use the result of __eq__() and invert it.
- Since x1 == x2 returned True, Python inverts it to False.
- So x1 != x2 results False.
class Test:
def __lt__(self, other):
return "Less"
def __gt__(self, other):
return "Greater"
print(3 < Test(), 3 > Test())- Normally, the 3 < Test() would try to call int.__lt__(3, Test()).
- Since int.__lt__() doesn’t know how to compare with Test, Python falls back to the reverse comparison with Test().__gt__(3).
- Inside the class, the __gt__() method is defined to return the string “Greater”.
- So, 3 < Test() evaluates to “Greater”.
- Python first tries int.__gt__(3, Test()).
- Again, since int.__gt__() does not know how to compare with Test, Python falls back to Test().__lt__(3).
- Inside the class, the __lt__() method returns “Less”.
- So, 3 > Test() evaluates to “Less”.
- Generally, the comparison methods (__lt__, __gt__, etc.) should return True or False.
- But the methods return strings, the result is “Greater” and “Less”.
class Animal:
def __contains__(self, item):
return len(item) == 3
print("cat" in Animal(), "doggy" in Animal())- The __contains__ method defines how the in operator works for instances of class Q.
- In this case, it returns True if the input item has a length of 3, otherwise, returns False.
- In the case of “cat” in Q(), the len(“cat”) == 3 returns True because “cat” has 3 characters.
- The len(“doggy”) == 3 returns False because “doggy” has 5 characters.
class Test:
def __init__(self):
self.data = {1: "One", 2: "Two"}
def __delitem__(self, key):
self.data.pop(key)
t = Test()
del t[1]
print(t.data)- When an instance of Test class is created, the __init__ method executes and self.data is set to {1: “One”, 2: “Two”}.
- When Python executes del t[1], Python internally calls t.__delitem__(1).
- In __delitem__ method, the self.data.pop(key) means self.data.pop(1).
- Therefore, the __delitem__(1) method removes the key 1 from the dictionary.




