Unit 5: Classes and objects; Object oriented programming terminology - Practice Quiz
1 Which keyword is used to create a class in Python?
2
Which statement correctly defines an empty class named Student?
3 Which special method is commonly used to initialize a new object's attributes?
__start__()
__main__()
__init__()
__create__()
4
Given class Car: pass, which statement creates an instance of Car?
5 What is an instance object?
6
In an instance method, what does the parameter self normally refer to?
7
If student has an attribute named name, how is that attribute accessed?
8
Which statement assigns the value 20 to the age attribute of person?
9 Which built-in function retrieves a named attribute from an object?
10 What does class inheritance allow a child class to do?
11
Which syntax defines Dog as a child class of Animal?
12
In class SavingsAccount(Account):, which class is the parent class?
13 What is method overriding?
14
A parent class and a child class both define display(). Which version is normally called on a child object?
15 Which function is commonly used to call a parent class method from a child class?
16 Which attribute name uses Python's double-underscore convention for data hiding?
17 What is the main purpose of data hiding in a class?
18
What happens to an attribute named __code inside a class named Product?
19 Does Python directly support traditional function overloading by defining several functions with the same name and different parameter lists?
20 Which Python feature can let one function accept different numbers of positional arguments?
*args parameter
global keyword
yield expression
break statement
21
What is printed by the following code?
class Counter:
total = 0
def __init__(self):
Counter.total += 1
Counter()
Counter()
c = Counter()
print(c.total)
22
Which class definition correctly initializes each Book object with separate title and price attributes?
class Book:\n def create(self, title, price):\n title = self.title\n price = self.price
class Book:\n def __init__(title, price):\n title.self = title\n price.self = price
class Book:\n def __init__(self, title, price):\n self.title = title\n self.price = price
class Book:\n def __init__(self, title, price):\n Book = title\n Book = price
23
What is the result of the following code?
class Rectangle:
def __init__(self, width, height=2):
self.width = width
self.height = height
def area(self):
return self.width * self.height
r = Rectangle(5)
print(r.area())
24
Given the class below, which statement creates a valid instance whose name is 'Asha'?
class Student:
def __init__(self, name):
self.name = name
s = Student('Asha')
s = Student.Student('Asha')
s = Student(self, 'Asha')
s = new Student('Asha')
25
What is printed by the following code?
class Box:
def __init__(self, value):
self.value = value
b1 = Box(4)
b2 = b1
b2.value = 9
print(b1.value, b2.value)
9 4
4 9
4 4
9 9
26
What does the expression p1 is p2 evaluate to?
class Point:
def __init__(self, x):
self.x = x
p1 = Point(3)
p2 = Point(3)
True, because they use the same class
True, because their attributes match
False, because x is immutable
False, because they are separate objects
27
What is printed by this code?
class Device:
category = 'electronic'
def __init__(self, category):
self.category = category
d = Device('sensor')
print(d.category, Device.category)
electronic electronic
sensor electronic
electronic sensor
sensor sensor
28
Which expression safely returns the salary attribute of employee, or 0 if that attribute does not exist?
employee.salary or 0
hasattr(employee, 'salary', 0)
employee.get('salary', 0)
getattr(employee, 'salary', 0)
29
What is printed by the following program?
class Account:
rate = 5
def __init__(self):
self.rate = 7
a = Account()
del a.rate
print(a.rate)
7
AttributeError
5
None
30
What is printed by this code?
class Vehicle:
wheels = 4
class Bike(Vehicle):
wheels = 2
class Scooter(Bike):
pass
print(Scooter.wheels)
AttributeError
4
2
None
31
What is the output of the following code?
class Parent:
def __init__(self, value):
self.value = value
class Child(Parent):
def __init__(self, value):
super().__init__(value * 2)
c = Child(6)
print(c.value)
8
12
36
6
32
Given class Manager(Employee, Auditor):, which statement best describes where Python first searches for an inherited method called by a Manager object?
Manager.__mro__
33
What is printed by this code?
class Animal:
def speak(self):
return 'sound'
class Dog(Animal):
def speak(self):
return 'bark'
a = Animal()
d = Dog()
print(a.speak(), d.speak())
sound bark
bark bark
bark sound
sound sound
34
What does PremiumBill.total() return?
class Bill:
def total(self):
return 100
class PremiumBill(Bill):
def total(self):
return super().total() + 20
b = PremiumBill()
100
120
20
80
35
Which method definition in Child overrides Parent.process while still reusing the parent's result?
class Parent:
def process(self, value):
return value * 2
def process(self): return super.process(value) + 1
def parent_process(self, value): return value * 2 + 1
def process(self, value): return super().process(value) + 1
def process(value): return Parent.process(value) + 1
36
What is the most likely result of directly evaluating v.__speed?
class Vehicle:
def __init__(self):
self.__speed = 60
v = Vehicle()
TypeError
None
AttributeError
60
37
Which expression accesses the name-mangled value of __balance from the object a?
class Account:
def __init__(self):
self.__balance = 500
a = Account()
a._Account__balance
a._balance
a.__balance
a.Account.__balance
38
What is printed by this code?
class Base:
def __init__(self):
self.__value = 10
class Child(Base):
def __init__(self):
super().__init__()
self.__value = 20
c = Child()
print(c._Base__value, c._Child__value)
20 20
10 10
20 10
10 20
39
What happens when this code runs?
class Calculator:
def add(self, a, b):
return a + b
def add(self, a, b, c):
return a + b + c
calc = Calculator()
print(calc.add(2, 3))
6
NameError
TypeError
5
40
Which implementation most directly supports calls such as area(5) for a square and area(5, 3) for a rectangle?
def area(a, b): return a * b if b else a * a
def area(a): return a * a\ndef area(a, b): return a * b
def area(*args): return args[0] + args[-1]
def area(a, b=None): return a * a if b is None else a * b
41
What is printed by the following code?
class A:
def __new__(cls):
print("new")
return object()
def __init__(self):
print("init")
a = A()
print(type(a).__name__)
new, then object
new, then init, then A
new, then A
new, then init, then object
42
What happens when this class definition is executed in Python 3?
class C:
x = 4
values = [x * i for i in range(3)]
C.values becomes [4, 4, 4]
UnboundLocalError occurs on first access
NameError occurs during class creation
C.values becomes [0, 4, 8]
43
What is printed by the following descriptor example?
class D:
def __get__(self, obj, owner):
return 10
def __set__(self, obj, value):
obj.__dict__["x"] = value * 2
class C:
x = D()
c = C()
c.x = 3
print(c.__dict__["x"], c.x)
6 6
6 10
3 3
3 10
44
What is printed by this code?
class C:
def __init__(self):
self.x = 5
def __getattribute__(self, name):
if name == "x":
raise AttributeError(name)
return object.__getattribute__(self, name)
def __getattr__(self, name):
return f"missing:{name}"
print(C().x)
missing:x
5
AttributeError
None
45
What is printed by this cooperative multiple-inheritance example?
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())
['D', 'B', 'A']
['D', 'B', 'C', 'A']
['D', 'B', 'A', 'C', 'A']
['D', 'C', 'A']
46
Given the following hierarchy, which implementation handles D().ping()?
class A:
def ping(self):
return "A"
class B(A):
pass
class C(A):
def ping(self):
return "C"
class D(B, C):
pass
A.ping, returning A
C.ping, returning C
B.ping, returning B
47
What happens when the final two statements execute?
class Base:
@classmethod
def identify(cls):
return cls.__name__
class Child(Base):
def identify(self):
return "instance"
print(Child().identify())
print(Child.identify())
instance, then Child
Child, then Child
TypeError before printing anything
instance, then raises TypeError
48
What is printed by this code?
class Box:
def __len__(self):
return 1
b = Box()
b.__len__ = lambda: 99
print(len(b), b.__len__())
1 1
99 1
1 99
99 99
49
What is printed by the following code using double-underscore names?
class A:
__value = 1
def get(self):
return self.__value
class B(A):
__value = 2
b = B()
print(b.get(), b._B__value)
1 2
1 1
2 2
2 1
50
What is printed after directly placing x in the instance dictionary?
class C:
@property
def x(self):
return 7
c = C()
c.__dict__["x"] = 20
print(c.x)
AttributeError
7
20
None
51
What happens when C().f(10) is evaluated?
class C:
def f(self, x):
return x
def f(self, x, y):
return x + y
TypeError for a missing argument
SyntaxError during class creation
20 using both definitions
10 using the first definition
52
What is the runtime result of the final call?
from typing import overload
@overload
def convert(x: int) -> str: ...
@overload
def convert(x: str) -> int: ...
def convert(x):
return x
print(convert(4))
NotImplementedError
4 as a string
4 as an integer
53
What does this singledispatch function print?
from functools import singledispatch
@singledispatch
def describe(value):
return "object"
@describe.register
def _(value: int):
return "integer"
print(describe(True))
KeyError
boolean
object
integer
54
What is printed when the metaclass modifies each new class namespace?
class Meta(type):
def __new__(mcls, name, bases, namespace):
namespace["x"] = namespace.get("x", 0) + 1
return super().__new__(mcls, name, bases, namespace)
class A(metaclass=Meta):
x = 4
class B(A):
pass
print(A.x, B.x)
4 1
5 5
4 4
5 1
55
What happens in this descriptor example?
class Descriptor:
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, owner):
return self.name
class C:
pass
C.x = Descriptor()
print(C().x)
AttributeError
None
TypeError
x
56
What is printed when an instance attribute has the same name as this descriptor?
class Descriptor:
def __get__(self, obj, owner):
return 10
class C:
x = Descriptor()
c = C()
c.__dict__["x"] = 30
print(c.x)
10
30
AttributeError
None
57
What list is printed after cooperative initialization?
class A:
def __init__(self, log):
log.append("A")
class B(A):
def __init__(self, log):
log.append("B")
super().__init__(log)
class C(A):
def __init__(self, log):
log.append("C")
super().__init__(log)
class D(B, C):
pass
log = []
D(log)
print(log)
['B', 'A', 'C', 'A']
['B', 'A']
['B', 'C', 'A']
['C', 'B', 'A']
58
What is printed when a subclass defines a method with the same private spelling?
class A:
def __run(self):
return "A"
def execute(self):
return self.__run()
class B(A):
def __run(self):
return "B"
print(B().execute())
None
A
AttributeError
B
59
What is printed after the augmented assignment and the ordinary assignment?
class C:
items = []
a = C()
b = C()
a.items += [1]
b.items = b.items + [2]
print(C.items, a.items, b.items)
[] [1] [1, 2]
[1] [1] [1, 2]
[1, 2] [1, 2] [1, 2]
[] [1] [2]
60
What happens when the final expression is evaluated?
class Base:
def value(self):
return 5
class Child(Base):
@property
def value(self):
return 8
result = Child().value()
result becomes 5
TypeError is raised
result becomes 8
AttributeError is raised
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 →