250+ TOP MCQs on Python Operator Overloading and Answers

Python Interview Questions and Answers for Experienced people on “Operator Overloading”

1. Which function is called when the following Python code is executed?

a) format()
b) __format__()
c) str()
d) __str__()
Answer: d
Clarification: Both str(f) and format(f) call f.__str__().

2. Which of the following Python code will print True?

a = foo(2)
b = foo(3)
print(a < b)

a)

class foo:
    def __init__(self, x):
        self.x = x
    def __lt__(self, other):
        if self.x < other.x:
            return False
        else:
            return True

b)

class foo:
    def __init__(self, x):
        self.x = x
    def __less__(self, other):
        if self.x > other.x:
            return False
        else:
            return True

c)

class foo:
    def __init__(self, x):
        self.x = x
    def __lt__(self, other):
        if self.x < other.x:
            return True
        else:
            return False

d)

class foo:
    def __init__(self, x):
        self.x = x
    def __less__(self, other):
        if self.x < other.x:
            return False
        else:
            return True

View Answer

Answer: c
Clarification: __lt__ overloads the < operator>.

 
 

3. Which function overloads the + operator?
a) __add__()
b) __plus__()
c) __sum__()
d) none of the mentioned
Answer: a
Clarification: Refer documentation.

4. Which operator is overloaded by __invert__()?
a) !
b) ~
c) ^
d) –
Answer: b
Clarification: __invert__() overloads ~.

5. Which function overloads the == operator?
a) __eq__()
b) __equ__()
c) __isequal__()
d) none of the mentioned
Answer: a
Clarification: The other two do not exist.

6. Which operator is overloaded by __lg__()?
a) <
b) >
c) !=
d) none of the mentioned
Answer: d
Clarification: __lg__() is invalid.

7. Which function overloads the >> operator?
a) __more__()
b) __gt__()
c) __ge__()
d) none of the mentioned
Answer: d
Clarification: __rshift__() overloads the >> operator.

8. Let A and B be objects of class Foo. Which functions are called when print(A + B) is executed?
a) __add__(), __str__()
b) __str__(), __add__()
c) __sum__(), __str__()
d) __str__(), __sum__()
Answer: a
Clarification: The function __add__() is called first since it is within the bracket. The function __str__() is then called on the object that we received after adding A and B.

9. Which operator is overloaded by the __or__() function?
a) ||
b) |
c) //
d) /
Answer: b
Clarification: The function __or__() overloads the bitwise OR operator |.

10. Which function overloads the // operator?
a) __div__()
b) __ceildiv__()
c) __floordiv__()
d) __truediv__()
Answer: c
Clarification: __floordiv__() is for //.

interview questions on Python for experienced people,

Leave a Reply

Your email address will not be published. Required fields are marked *