Unit 4: More on OOP concepts - Practice Quiz
1 What does function overloading generally mean?
2 Does Python directly support traditional function overloading based only on parameter lists?
3 What happens when multiple functions with the same name are defined in the same Python scope?
4 Which Python feature can imitate function overloading by allowing an argument to be omitted?
5 Which parameter syntax allows a Python function to accept a variable number of positional arguments?
*args
**args
@args
&args
6 What is a common benefit of function overloading?
7 Which standard-library decorator supports dispatch based on the type of the first argument?
@classmethod
@staticmethod
@singledispatch
@property
8 What is operator overloading in Python?
9
Which special method overloads the + operator?
__sub__()
__eq__()
__add__()
__mul__()
10
Which special method overloads the - operator?
__div__()
__add__()
__mod__()
__sub__()
11
Which special method is associated with the == operator?
__lt__()
__ne__()
__gt__()
__eq__()
12
Which special method is called for the * operator?
__mod__()
__truediv__()
__matmul__()
__mul__()
13
What is another common name for methods such as __add__() and __sub__()?
14
If a + b is evaluated and a defines __add__(), which call does Python try?
b.__sub__(a)
a.__add__(b)
b.__add__(a)
a.__sub__(b)
15
Which built-in type demonstrates + with both arithmetic and concatenation behavior?
range
str
set
bool
16 What is method overriding?
17 Which object-oriented concept is required for method overriding?
18 When an overridden method is called on a child-class object, which version normally runs?
19 Which function can a child class use to call the parent class implementation?
open()
super()
type()
input()
20 What does method overriding help a child class do?
21
What does the following code print?
def calculate(a, b):
return a + b
def calculate(a, b, c):
return a + b + c
print(calculate(2, 3))
5
None
6
TypeError is raised
22 Which definition best simulates overloading a function so that it can add either two or three numbers?
def add(a, b, c): return a + b + c
def add(a=0): return a + a
def add(a, b, c=0): return a + b + c
def add(a, b): return a + b + b
23
What is the output of this code?
def total(*values):
return sum(values)
print(total(2, 4, 6))
12
10
6
24
24 A function must format either one name or a first name followed by a last name. Which signature is most suitable?
def format_name(first=None):
def format_name(first, last):
def format_name(*, first):
def format_name(first, last=None):
25
Given the function below, which call returns 6?
def multiply(a, b=2, c=1):
return a b c
multiply(2, 2, 2)
multiply(a=1, c=3)
multiply(3, 3)
multiply(3)
26 Which approach provides type-based function dispatch using Python's standard library?
functools.singledispatch
staticmethod
27
What does this function return for describe("Python")?
def describe(value):
if isinstance(value, str):
return len(value)
return value * 2
PythonPython
12
TypeError is raised
6
28
Which special method should a class implement to customize the behavior of the + operator?
__add__
__sum__
__plus__
__concat__
29
What does the following code print?
class Score:
def init(self, value):
self.value = value
def add(self, other):
return Score(self.value + other.value)
result = Score(7) + Score(5)
print(result.value)
12
Score(12)
2
35
30
A Vector class should support 3 * vector when it already supports vector * 3 through __mul__. Which method should normally be added?
__radd__
__imul__
__rmul__
__matmul__
31
What should __add__ usually return when it cannot handle the type of the other operand?
None
NotImplemented
NotImplementedError
False
32
Which special method is invoked by a == b to test value equality?
__cmp__
__same__
__is__
__eq__
33
What is printed by the following code?
class Box:
def init(self, items):
self.items = items
def len(self):
return len(self.items) * 2
print(len(Box([1, 2, 3])))
3
6
5
2
34
What is the main behavioral difference between __add__ and __iadd__?
__add__ is reflected, while __iadd__ is inherited
__add__ handles +, while __iadd__ handles +=
__add__ compares values, while __iadd__ adds values
__add__ handles +=, while __iadd__ handles +
35
What does this code print?
class Animal:
def speak(self):
return "sound"
class Dog(Animal):
def speak(self):
return "bark"
pet = Dog()
print(pet.speak())
bark
soundbark
TypeError is raised
sound
36
What is printed by this code?
class Parent:
def message(self):
return "Parent"
class Child(Parent):
def message(self):
return super().message() + " Child"
print(Child().message())
Child
Child Parent
Parent Child
Parent
37 Which condition is essential for a subclass method to override an inherited instance method?
super first
override
38
What does the following code print?
class Report:
def title(self):
return "General"
class SalesReport(Report):
pass
print(SalesReport().title())
AttributeError is raised
SalesReport
None
General
39
Consider the classes below. What does process(EmailNotification()) return?
class Notification:
def send(self):
return "default"
class EmailNotification(Notification):
def send(self):
return "email"
def process(item):
return item.send()
EmailNotification
default
Notification
email
40
What is the result of calling Manager().work()?
class Employee:
def work(self, hours=4):
return hours
class Manager(Employee):
def work(self, hours=4):
return super().work(hours) * 2
8
16
2
4
41
What does the following program print?
def f(x):
return x + 1
g = f
def f(x, y=3):
return x * y
print(g(4), f(4))
TypeError
5 12
5 7
12 12
42
What is printed at runtime?
from typing import overload
@overload
def convert(x: int) -> str: ...
@overload
def convert(x: str) -> int: ...
def convert(x):
return x * 2
print(convert("7"), convert(7))
TypeError
7 14
14 77
77 14
43
Which handler is selected by this singledispatch call?
from functools import singledispatch
@singledispatch
def label(x):
return "object"
@label.register(int)
def _(x):
return "int"
print(label(True))
object
bool and int
bool
int
44
What is the result of the final call?
from functools import singledispatch
@singledispatch
def combine(a, b):
return "base"
@combine.register(int)
def (a, b):
return "int:" + type(b).name
@combine.register(str)
def (a, b):
return "str:" + type(b).name
print(combine(1, "x"))
base
str:int
str:str
int:str
45
What does this program print?
from functools import singledispatchmethod
class Renderer:
@singledispatchmethod
def render(self, value, mode):
return "base"
@render.register
def _(self, value: int, mode):
return "int"
print(Renderer().render(True, "brief"))
base
int
bool
TypeError
46
What is printed by the following class definition?
class Calculator:
def calc(self, x):
return x * 10
@staticmethod
def calc(x, y=1):
return x + y
print(Calculator().calc(3))
30
3
4
TypeError
47
What does this program print?
trace = []
class A:
def add(self, other):
trace.append("A.add")
return "left"
class B(A):
def radd(self, other):
trace.append("B.radd")
return "right"
print(A() + B(), trace)
right ['A.__add__', 'B.__radd__']
TypeError ['A.__add__']
left ['A.__add__']
right ['B.__radd__']
48
What is the outcome of x + x?
log = []
class X:
def add(self, other):
log.append("add")
return NotImplemented
def radd(self, other):
log.append("radd")
return 9
x = X()
try:
x + x
except TypeError:
print(log)
9 after logging ['radd']
TypeError after logging ['add']
TypeError after logging ['radd']
9 after logging ['add', 'radd']
49
What does the final statement print?
class Box:
def init(self, value):
self.value = value
def add(self, other):
return Box(self.value + other)
a = Box(2)
b = a
a += 3
print(a.value, b.value, a is b)
2 2 False
5 2 False
5 2 True
5 5 True
50
What happens when the final line executes?
class Key:
def init(self, value):
self.value = value
def eq(self, other):
return isinstance(other, Key) and self.value == other.value
k = Key(3)
print(hash(k))
hash(3)
AttributeError for a missing method
k
TypeError because k is unhashable
51
What is printed by this comparison?
log = []
class A:
def lt(self, other):
log.append("A.lt")
return "left"
class B(A):
def gt(self, other):
log.append("B.gt")
return "right"
print(A() < B(), log)
right ['A.__lt__', 'B.__gt__']
right ['B.__gt__']
TypeError []
left ['A.__lt__']
52
What are the values of events and result.tag?
events = []
class Token:
def init(self, tag):
self.tag = tag
def bool(self):
events.append("bool " + self.tag)
return False
class N:
def init(self, name):
self.name = name
def lt(self, other):
tag = self.name + other.name
events.append("lt " + tag)
return Token(tag)
result = N("a") < N("b") < N("c")
['lt ab', 'lt bc'] and bc
['lt ab', 'bool ab'] and ab
['lt ab', 'bool ab', 'lt bc'] and bc
['lt ab'] and ab
53
What does the following program print?
class Bag:
def getitem(self, index):
if index >= 3:
raise IndexError
return (4, 6, 8)[index]
print(6 in Bag(), 5 in Bag())
False False
True True
True False
TypeError
54
What does D().m() return under Python's method resolution order?
class A:
def m(self):
return ["A"]
class B(A):
def m(self):
return ["B"] + super().m()
class C(A):
def m(self):
return ["C"] + super().m()
class D(B, C):
pass
['B', 'A']
['B', 'A', 'C']
['B', 'C', 'A']
['C', 'A']
55
How does changing C.m affect the result?
class A:
def m(self):
return ["A"]
class B(A):
def m(self):
return ["B"] + super().m()
class C(A):
def m(self):
return ["C"]
class D(B, C):
pass
result = D().m()
result is ['B', 'A']
result is ['B', 'C']
result is ['B', 'C', 'A']
result is ['C', 'B', 'A']
56
What is returned by Sub().call()?
class Base:
def call(self):
return self.step()
def step(self):
return "base"
class Sub(Base):
def __step(self):
return "sub"
result = Sub().call()
AttributeError because __step is private
sub because self has type Sub
sub because instance methods are virtual
base because the names are mangled separately
57
What does Sub().f() return?
class Base:
def f(self, x=1):
return f"B{x}"
class Sub(Base):
def f(self, x=2):
return super().f() + f"/S{x}"
B2/S2
B2/S1
B1/S1
B1/S2
58
What does constructing Sub() print?
class Base:
def init(self):
self.configure()
def configure(self):
print("base")
class Sub(Base):
def init(self):
super().init()
self.ready = True
def configure(self):
print(getattr(self, "ready", "missing"))
Sub()
True
AttributeError
base
missing
59
What happens at s.x = 3?
class Base:
def init(self):
self._x = 1
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
class Sub(Base):
@property
def x(self):
return self._x * 10
s = Sub()
s.x = 3
s._x remains silently unchanged
AttributeError is raised
s.x becomes 30
s.x becomes 3
60
What is the outcome of the final expression?
from abc import ABC, abstractmethod
class A(ABC):
@abstractmethod
def f(self):
return "A"
class B(A):
def f(self):
return super().f() + "B"
result = B().f()
AB because the abstract implementation is callable
A because the abstract method takes precedence
TypeError because super().f() remains abstract
B because abstract methods have no callable body
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →