Unit 3: OOP concepts - Practice Quiz
1 What is a class in Python?
2 What is an object in object-oriented programming?
3 Which special method commonly initializes a new Python object?
__create__()
__init__()
__main__()
__start__()
4
What does the self parameter represent in an instance method?
5 What is a method in a Python class?
6 Which OOP feature allows one interface to support different behaviors?
7 Which OOP feature focuses on showing essential behavior while hiding implementation details?
8 What is encapsulation in object-oriented programming?
9 Which Python naming style indicates that an attribute is intended for internal use?
10
What happens to an instance attribute named __balance inside a Python class?
11 What is the usual purpose of a getter method?
12 What is the usual purpose of a setter method?
13 Which Python feature can provide controlled access to an attribute using method-like logic?
14 Which built-in decorator is commonly used to define a property getter?
@property
@staticmethod
@classmethod
@abstractmethod
15 What does inheritance allow a Python class to do?
16
In class Dog(Animal):, which class is the parent class?
object
class
Dog
Animal
17
In class Dog(Animal):, which class is the child class?
Animal
Dog
class
object
18 Which function is commonly used to access a parent class implementation?
inherit()
base()
super()
parent()
19 What is method overriding?
20 What is multiple inheritance in Python?
21
What is printed by the following code?
class Wallet:
def __init__(self, amount):
self.amount = amount
def add(self, value):
self.amount += value
w1 = Wallet(100)
w2 = Wallet(100)
w1.add(50)
print(w1.amount, w2.amount)
100 100
150 100
100 150
150 150
22
What is the output of this polymorphic code?
class Dog:
def speak(self):
return 'Woof'
class Cat:
def speak(self):
return 'Meow'
animals = [Dog(), Cat()]
print([animal.speak() for animal in animals])
['Woof', 'Meow']
['Meow', 'Woof']
['Woof', 'Woof']
['Meow', 'Meow']
23
A Car object creates and stores an Engine object as self.engine. Which OOP relationship does this primarily represent?
24
What is printed by the following code?
class Counter:
total = 0
def __init__(self):
Counter.total += 1
c1 = Counter()
c2 = Counter()
c1.total = 10
print(c1.total, c2.total, Counter.total)
10 2 10
10 2 2
2 2 10
10 10 2
25
Which method should be implemented so that print(book) displays a student-friendly description of a Book object?
__init__()
__call__()
__str__()
__new__()
26
A function calls shape.area() on objects from unrelated classes without checking their types. Which Python OOP feature makes this design practical?
27
What happens when this code executes?
from abc import ABC, abstractmethod
class Report(ABC):
@abstractmethod
def generate(self):
pass
class SalesReport(Report):
pass
r = SalesReport()
TypeError is raised
None
28
What happens when the final statement executes?
class Account:
def __init__(self):
self.__balance = 500
a = Account()
print(a.__balance)
500 is printed normally
NameError is raised
None is printed normally
AttributeError is raised
29
What is the result of assigning p.price = -20?
class Product:
def __init__(self, price):
self._price = price
@property
def price(self):
return self._price
@price.setter
def price(self, value):
if value < 0:
raise ValueError('Invalid price')
self._price = value
p = Product(50)
p.price = -20
AttributeError is raised
50 silently
-20
ValueError is raised
30
What does a single leading underscore in an attribute such as self._score indicate in Python?
31
What happens at the final statement?
class Temperature:
def __init__(self, value):
self._value = value
@property
def value(self):
return self._value
t = Temperature(25)
t.value = 30
AttributeError is raised
30
32
What is printed by this code?
class Config:
__mode = 'safe'
@classmethod
def get_mode(cls):
return cls.__mode
print(Config.get_mode(), hasattr(Config, '__mode'))
safe True
safe False
None True
None False
33
What does the following code print?
class Base:
def __value(self):
return 'Base'
def show(self):
return self.__value()
class Child(Base):
def __value(self):
return 'Child'
print(Child().show())
BaseChild
Base
None
Child
34
What is printed by the final statement?
class Cart:
def __init__(self):
self.__items = []
@property
def items(self):
return self.__items.copy()
cart = Cart()
view = cart.items
view.append('pen')
print(cart.items)
None
['pen']
[]
AttributeError
35
What is printed by this code?
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
def __init__(self, name, grade):
super().__init__(name)
self.grade = grade
s = Student('Asha', 9)
print(s.name, s.grade)
AttributeError
Asha 9
None 9
Asha None
36
What does this overridden method return?
class Parent:
def message(self):
return 'P'
class Child(Parent):
def message(self):
return super().message() + 'C'
print(Child().message())
C
PC
CP
P
37
What is printed according to Python's method resolution order?
class A:
def run(self):
print('A', end=' ')
class B(A):
def run(self):
print('B', end=' ')
super().run()
class C(A):
def run(self):
print('C', end=' ')
super().run()
class D(B, C):
pass
D().run()
B A C
C B A
B C A
A B C
38
What is printed by the following code?
class Base:
rate = 5
class Child(Base):
pass
c1 = Child()
c2 = Child()
c1.rate = 8
print(c2.rate, Base.rate)
8 5
5 8
8 8
5 5
39
What does this code print?
class Base:
pass
class Child(Base):
pass
obj = Child()
print(isinstance(obj, Child), isinstance(obj, Base), type(obj) is Base)
True False False
False True True
True True True
True True False
40
What is printed by the following code?
class Base:
def greet(self):
return 'Base'
class Child(Base):
def greet(self):
return 'Child'
c = Child()
print(c.greet(), super(Child, c).greet())
Child Child
Child Base
Base Base
Base Child
41
What does the following code print?
class A:
items = []
def add(self, value):
self.items += [value]
a = A()
b = A()
a.add(1)
print(A.items, b.items, a.items is b.items)
[] [1] False
[] [] False
[1] [1] True
[1] [] True
42
What does the following code print?
class A:
def __f(self):
return "A"
def call(self):
return self.__f()
class B(A):
def __f(self):
return "B"
print(B().call())
B
A
AB
AttributeError
43
What is printed when both a base class and its subclass declare a private slot with the same source-level name?
class A:
__slots__ = ("__x",)
def __init__(self):
self.__x = 1
def from_a(self):
return self.__x
class B(A):
__slots__ = ("__x",)
def __init__(self):
super().__init__()
self.__x = 2
def from_b(self):
return self.__x
b = B()
print(b.from_a(), b.from_b())
2 2
AttributeError
1 2
1 1
44
What does this code print?
class C:
@property
def x(self):
return 10
c = C()
c.__dict__["x"] = 99
print(c.x, c.__dict__["x"])
10 99
AttributeError
10 10
99 99
45
What is the result of this managed attribute lookup?
class C:
@property
def x(self):
raise AttributeError("hidden")
def __getattr__(self, name):
return f"fallback:{name}"
print(C().x)
hidden
None
fallback:x
AttributeError
46
What does the following code print?
class Base:
@property
def x(self):
return 1
class Child(Base):
x = 5
c = Child()
c.x = 9
print(c.x)
AttributeError
9
5
1
47
What does Python print for this cooperative diamond hierarchy?
class A:
def f(self):
return "A"
class B(A):
def f(self):
return "B" + super().f()
class C(A):
def f(self):
return "C" + super().f()
class D(B, C):
def f(self):
return "D" + super().f()
print(D().f())
DCBA
DBCA
DBAC
DBA
48
What is the final trace produced by these cooperative initializers?
class A:
def __init__(self, **kwargs):
self.trace = ["A"]
super().__init__(**kwargs)
class B(A):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.trace.append("B")
class C(A):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.trace.append("C")
class D(B, C):
def __init__(self):
super().__init__()
self.trace.append("D")
print(D().trace)
['A', 'C', 'D', 'B']
['D', 'B', 'C', 'A']
['A', 'B', 'C', 'D']
['A', 'C', 'B', 'D']
49
At which statement does Python first raise an exception?
class X:
pass
class Y:
pass
class A(X, Y):
pass
class B(Y, X):
pass
class C(A, B):
pass
A
C()
B
C
50
What does this class-method call return?
class A:
@classmethod
def who(cls):
return cls.__name__
class B(A):
@classmethod
def who(cls):
return super().who() + ":B"
print(B.who())
B:B
B:A
A:A
A:B
51
What happens in this abstract-base-class example?
from abc import ABC, abstractmethod
class A(ABC):
@abstractmethod
def f(self):
return "A"
class B(A):
def f(self):
return super().f() + "B"
print(B().f())
A
AB
TypeError
B
52
Which result correctly describes this virtual subclass registration?
from abc import ABC, abstractmethod
class Protocol(ABC):
@abstractmethod
def run(self):
pass
class Worker:
pass
Protocol.register(Worker)
w = Worker()
isinstance(w, Protocol) is false, but w.run() returns None
isinstance(w, Protocol) is true, and w.run() returns None
isinstance(w, Protocol) is false, and w.run() raises AttributeError
isinstance(w, Protocol) is true, but w.run() raises AttributeError
53
What does this code print after mutation through one subclass and rebinding through another?
class A:
data = []
class B(A):
pass
class C(A):
pass
B.data.append(1)
C.data = C.data + [2]
print(A.data, B.data, C.data)
[1] [1] [1, 2]
[1, 2] [1, 2] [1, 2]
[1] [1, 2] [1, 2]
[] [1] [2]
54
Which special method handles the following addition?
class A:
def __add__(self, other):
return "A.__add__"
class B(A):
def __radd__(self, other):
return "B.__radd__"
print(A() + B())
B.__add__
B.__radd__
A.__add__
TypeError
55
What happens when hash(B()) is evaluated?
class A:
def __hash__(self):
return 7
class B(A):
def __eq__(self, other):
return True
True
7
TypeError
56
What does this code print?
class C:
def __len__(self):
return 3
c = C()
c.__len__ = lambda: 9
print(len(c), c.__len__())
3 3
9 3
3 9
9 9
57
What is printed by this singleton-style implementation?
class C:
_one = None
def __new__(cls):
if cls._one is None:
cls._one = super().__new__(cls)
return cls._one
def __init__(self):
self.n = getattr(self, "n", 0) + 1
a = C()
b = C()
print(a is b, a.n)
False 2
False 1
True 1
True 2
58
After executing the setup below, which expression raises TypeError?
class C:
def f(self, x):
return x
c = C()
c.g = C.f
c.g(3)
c.f(3)
c.g(c, 3)
C.f(c, 3)
59
What happens when the copied method is called?
class A:
def ping(self):
return "A"
class B(A):
def ping(self):
return super().ping() + "B"
class C(A):
ping = B.ping
print(C().ping())
AB
A
TypeError
AttributeError
60
What does this descriptor example print?
class Label:
def __get__(self, obj, owner):
return "descriptor"
class C:
x = Label()
c = C()
c.x = "instance"
print(c.x)
None
AttributeError
instance
descriptor
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 →