25 Python Operator Overloading MCQ – Quiz Questions
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.👇
1. What is operator overloading in Python?
A. Changing the precedence of operators.
B. Using one operator for multiple data types.
C. Changing the default behavior of an operator depending on the operands being used.
D. Changing the behavior of existing operators for built-in types.
c
The process of changing the default behavior of an operator depending on the operands being used is called operator overloading in Python.
2. Which method is used to overload the + operator in Python?
A. __add__()
B. __plus__()
C. add()
D. __concat__()
a
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.
3. What will be the output of the following code?
class A: def __add__(self, other): return "Addition done" a = A() print(a + a)
A. 2a
B. Addition done
C. None
D. TypeError
b
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.
4. Which operator can be overloaded using __eq__()?
A. =
B. !=
C. ==
D. is
c
The special magic method __eq__() is used to define behavior for the equality operator ==.
5. Can Python overload logical operators like and, or, and not?
A. Yes, using __and__, __or__, __not__
B. No
C. Only and
D. Only with lambda functions
b
Logical operators cannot be overloaded directly in Python.
6. Which of the following can be used to overload the * operator?
A. __pow__
B. __mod__
C. __mul__
D. __divmod__
c
__mul__ is the method used to overload multiplication (*) operator.
7. What will be the output of the following code?
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)
A. 20
B. 20 + 30
C. 50
D. TypeError
c
Refer to Operator Overloading in Python chapter for exact explanation.
8. Which method is used to overload the greater than operator (>) in Python?
A. __gt__()
B. __lt__()
C. __ge__()
D. __cmp__()
a
__gt__ stands for “greater than” and is used to overload the > operator.
9. What will be the output of the following Python code?
class Test: def __eq__(self, other): return True print(Test() == Test())
A. True
B. False
C. TypeError
D. None
a
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.
10. What will be the expected output of the following Python code if no error?
class Test: def __mul__(self, other): return "Hello" t = Test() print(t * 3)
A. HelloHelloHello
B. Hello
C. Hello3
D. TypeError
b
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”.
11. What will happen if you don’t define __eq__ in your class and compare two instances of the class using ==?
A. Always True
B. Always False
C. Default comparison based on identity
D. Error
c
Without __eq__() method, the equality operator == compares memory locations (i.e. object identity).
12. Which operator is overloaded by the __truediv__(self, other) method in Python?
A. //
B. /
C. %
D. **
b
The __truediv__() magic method overloads the true division operator (/), which performs floating-point division operation.
13. What will be the output of the following Python code?
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)
A. Point(8, 27)
B. Point(2, 3)
C. Point(4, 9)
D. TypeError
c
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.
14. Which method is used to overload in keyword?
A. __hasitem__()
B. __include__()
C. __in__()
D. __contains__()
d
The membership operator “in” is overloaded by defining the __contains__() magic method within a class.
15. Which special method would you implement to make the expression obj1 += obj2 work?
A. __iadd__()
B. __add__()
C. __plus_equals__()
D. Both A and B
a
The __iadd__() method is used for the += operator. If this method is not implemented, Python will fall back to using __add__() method and then reassign the result to the left-hand variable.
16. What do you expect the output of the following Python code?
class Test: def __radd__(self, other): return other + 10 t = Test() print(5 + t)
A. 10
B. 15
C. TypeError
D. None
b
When Python interpreter executes 5 + A(), it internally triggers A.__radd__(5) which returns 15. The purpose of the __radd__() method is to handle right-side addition when the left operand doesn’t support addition.
17. Which of the following operator is not overloadable in Python?
A. +
B. **
C. //
D. is
d
Identity (is) and logical operators (and, or, not) can’t be overloaded.
18. Identify the output of the following Python code.
class A: def __mul__(self, other): return "Hi" def __rmul__(self, other): return "Bye" print(5 * A())
A. Hi
B. Bye
C. HiHiHiHiHi
D. ByeByeByeByeBye
b
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.
19. What is the output of the below Python code?
class Number: def __pow__(self, exponent): return exponent - 1 n = Number() print(n ** 3)
A. 9
B. 2
C. 8
D. TypeError
b
n ** 3 calls Num.__pow__(3) which returns 3 – 1 = 2.
20. Predict the output of the following code.
class Test: def __sub__(self, other): return "Left Sub" def __rsub__(self, other): return "Right Sub" print(Test() - 2) print(2 - Test())
A. “Left Sub” and “Right Sub”
B. “Right Sub” and “Left Sub”
C. Both “Left Sub”
D. TypeError
a
Python will first call __sub__() method, then call the second method __rsub__().
21. Predict the output of the following Python code if no error is found.
class Number: def __eq__(self, other): return self.value == other.value n1 = Number() n1.value = 10 n2 = Number() print(n1 == n2)
A. True
B. False
C. AttributeError
D. TypeError
c
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.
22. What will be the result of the following Python code?
class X: def __eq__(self, other): return True x1 = X() x2 = X() print(x1 == x2, x1 != x2)
A. True True
B. True False
C. False True
D. False False
b
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.
23. Which of the following output is correct for the below Python code?
class Test: def __lt__(self, other): return "Less" def __gt__(self, other): return "Greater" print(3 < Test(), 3 > Test())
A. Less Greater
B. Greater Less
C. True False
D. TypeError
b
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”.
24. Identify the output of the following Python code.
class Animal: def __contains__(self, item): return len(item) == 3 print("cat" in Animal(), "doggy" in Animal())
A. True True
B. True False
C. False True
D. False False
b
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.
25. What will be the expected output of the following code if no error is present?
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)
A. {}
B. {1: “One”}
C. {2: “Two”}
D. TypeError
c
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.
Quiz Results
0
Total Questions
0
Correct Answers
0
Incorrect Answers
0%
Score