Unit 3: OOP concepts - Practice Quiz

ECAP776 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 What is a class in Python?

OOP features Easy
A. A condition for selecting statements
B. A blueprint for creating objects
C. A loop for repeating statements
D. A module for importing packages

2 What is an object in object-oriented programming?

OOP features Easy
A. An instance of a class
B. A definition of a loop
C. An alternative to a function
D. A collection of modules

3 Which special method commonly initializes a new Python object?

OOP features Easy
A. __init__()
B. __main__()
C. __create__()
D. __start__()

4 What does the self parameter represent in an instance method?

OOP features Easy
A. The current object
B. The global namespace
C. The parent class
D. The imported module

5 What is a method in a Python class?

OOP features Easy
A. A loop executed before a class
B. A module imported into a class
C. A function defined inside a class
D. A variable defined outside a class

6 Which OOP feature allows one interface to support different behaviors?

OOP features Easy
A. Compilation
B. Polymorphism
C. Tokenization
D. Iteration

7 Which OOP feature focuses on showing essential behavior while hiding implementation details?

OOP features Easy
A. Recursion
B. Abstraction
C. Concatenation
D. Iteration

8 What is encapsulation in object-oriented programming?

Encapsulation Easy
A. Repeating statements within one loop
B. Converting values into one type
C. Bundling data and methods in one class
D. Importing functions from one module

9 Which Python naming style indicates that an attribute is intended for internal use?

Encapsulation Easy
A. A single trailing asterisk
B. A single leading asterisk
C. A single trailing underscore
D. A single leading underscore

10 What happens to an instance attribute named __balance inside a Python class?

Encapsulation Easy
A. It becomes a class method
B. It becomes a global variable
C. It undergoes type conversion
D. It undergoes name mangling

11 What is the usual purpose of a getter method?

Encapsulation Easy
A. To import an attribute value
B. To remove an attribute value
C. To retrieve an attribute value
D. To repeat an attribute value

12 What is the usual purpose of a setter method?

Encapsulation Easy
A. To delete an attribute owner
B. To display an attribute name
C. To update an attribute value
D. To inherit an attribute type

13 Which Python feature can provide controlled access to an attribute using method-like logic?

Encapsulation Easy
A. A comment
B. A property
C. A module
D. A loop

14 Which built-in decorator is commonly used to define a property getter?

Encapsulation Easy
A. @staticmethod
B. @abstractmethod
C. @property
D. @classmethod

15 What does inheritance allow a Python class to do?

Inheritance Easy
A. Hide every local variable
B. Reuse features of another class
C. Repeat every method in a loop
D. Convert objects into modules

16 In class Dog(Animal):, which class is the parent class?

Inheritance Easy
A. Dog
B. object
C. Animal
D. class

17 In class Dog(Animal):, which class is the child class?

Inheritance Easy
A. Animal
B. Dog
C. object
D. class

18 Which function is commonly used to access a parent class implementation?

Inheritance Easy
A. super()
B. base()
C. inherit()
D. parent()

19 What is method overriding?

Inheritance Easy
A. Calling a child method from a parent class
B. Deleting a method from every class
C. Importing a method from another module
D. Redefining a parent method in a child class

20 What is multiple inheritance in Python?

Inheritance Easy
A. A class inheriting from several parent classes
B. A method called several times
C. Several attributes sharing one value
D. Several objects created from one class

21 What is printed by the following code?

PYTHON
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)

OOP features Medium
A. 150 100
B. 100 100
C. 100 150
D. 150 150

22 What is the output of this polymorphic code?

PYTHON
class Dog:
    def speak(self):
        return 'Woof'

class Cat:
    def speak(self):
        return 'Meow'

animals = [Dog(), Cat()]
print([animal.speak() for animal in animals])

OOP features Medium
A. ['Meow', 'Woof']
B. ['Meow', 'Meow']
C. ['Woof', 'Woof']
D. ['Woof', 'Meow']

23 A Car object creates and stores an Engine object as self.engine. Which OOP relationship does this primarily represent?

OOP features Medium
A. Inheritance
B. Method overriding
C. Composition
D. Data abstraction

24 What is printed by the following code?

PYTHON
class Counter:
    total = 0

    def __init__(self):
        Counter.total += 1

c1 = Counter()
c2 = Counter()
c1.total = 10
print(c1.total, c2.total, Counter.total)

OOP features Medium
A. 10 2 10
B. 10 2 2
C. 2 2 10
D. 10 10 2

25 Which method should be implemented so that print(book) displays a student-friendly description of a Book object?

OOP features Medium
A. __str__()
B. __new__()
C. __init__()
D. __call__()

26 A function calls shape.area() on objects from unrelated classes without checking their types. Which Python OOP feature makes this design practical?

OOP features Medium
A. Constructor chaining
B. Name mangling
C. Duck typing
D. Class shadowing

27 What happens when this code executes?

PYTHON
from abc import ABC, abstractmethod

class Report(ABC):
    @abstractmethod
    def generate(self):
        pass

class SalesReport(Report):
    pass

r = SalesReport()

OOP features Medium
A. The abstract method returns None
B. A TypeError is raised
C. An empty object is created
D. A warning is printed

28 What happens when the final statement executes?

PYTHON
class Account:
    def __init__(self):
        self.__balance = 500

a = Account()
print(a.__balance)

Encapsulation Medium
A. 500 is printed normally
B. An AttributeError is raised
C. None is printed normally
D. A NameError is raised

29 What is the result of assigning p.price = -20?

PYTHON
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

Encapsulation Medium
A. A ValueError is raised
B. The price becomes -20
C. The price remains 50 silently
D. An AttributeError is raised

30 What does a single leading underscore in an attribute such as self._score indicate in Python?

Encapsulation Medium
A. It is intended for internal use
B. It is inaccessible outside the class
C. It is shared by all instances
D. It is automatically read-only

31 What happens at the final statement?

PYTHON
class Temperature:
    def __init__(self, value):
        self._value = value

    @property
    def value(self):
        return self._value

t = Temperature(25)
t.value = 30

Encapsulation Medium
A. The value changes to 30
B. A new property is created
C. An AttributeError is raised
D. The assignment is ignored

32 What is printed by this code?

PYTHON
class Config:
    __mode = 'safe'

    @classmethod
    def get_mode(cls):
        return cls.__mode

print(Config.get_mode(), hasattr(Config, '__mode'))

Encapsulation Medium
A. safe True
B. None True
C. safe False
D. None False

33 What does the following code print?

PYTHON
class Base:
    def __value(self):
        return 'Base'

    def show(self):
        return self.__value()

class Child(Base):
    def __value(self):
        return 'Child'

print(Child().show())

Encapsulation Medium
A. None
B. Child
C. BaseChild
D. Base

34 What is printed by the final statement?

PYTHON
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)

Encapsulation Medium
A. None
B. An AttributeError
C. []
D. ['pen']

35 What is printed by this code?

PYTHON
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)

Inheritance Medium
A. Asha 9
B. None 9
C. Asha None
D. An AttributeError

36 What does this overridden method return?

PYTHON
class Parent:
    def message(self):
        return 'P'

class Child(Parent):
    def message(self):
        return super().message() + 'C'

print(Child().message())

Inheritance Medium
A. PC
B. CP
C. P
D. C

37 What is printed according to Python's method resolution order?

PYTHON
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()

Inheritance Medium
A. A B C
B. C B A
C. B C A
D. B A C

38 What is printed by the following code?

PYTHON
class Base:
    rate = 5

class Child(Base):
    pass

c1 = Child()
c2 = Child()
c1.rate = 8
print(c2.rate, Base.rate)

Inheritance Medium
A. 8 5
B. 5 5
C. 5 8
D. 8 8

39 What does this code print?

PYTHON
class Base:
    pass

class Child(Base):
    pass

obj = Child()
print(isinstance(obj, Child), isinstance(obj, Base), type(obj) is Base)

Inheritance Medium
A. False True True
B. True True False
C. True True True
D. True False False

40 What is printed by the following code?

PYTHON
class Base:
    def greet(self):
        return 'Base'

class Child(Base):
    def greet(self):
        return 'Child'

c = Child()
print(c.greet(), super(Child, c).greet())

Inheritance Medium
A. Child Base
B. Base Child
C. Child Child
D. Base Base

41 What does the following code print?

PYTHON
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)

OOP features Hard
A. [1] [] True
B. [1] [1] True
C. [] [] False
D. [] [1] False

42 What does the following code print?

PYTHON
class A:
    def __f(self):
        return "A"

    def call(self):
        return self.__f()

class B(A):
    def __f(self):
        return "B"

print(B().call())

Encapsulation Hard
A. AB
B. AttributeError
C. B
D. A

43 What is printed when both a base class and its subclass declare a private slot with the same source-level name?

PYTHON
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())

Encapsulation Hard
A. 1 2
B. 2 2
C. 1 1
D. AttributeError

44 What does this code print?

PYTHON
class C:
    @property
    def x(self):
        return 10

c = C()
c.__dict__["x"] = 99
print(c.x, c.__dict__["x"])

Encapsulation Hard
A. 99 99
B. 10 99
C. AttributeError
D. 10 10

45 What is the result of this managed attribute lookup?

PYTHON
class C:
    @property
    def x(self):
        raise AttributeError("hidden")

    def __getattr__(self, name):
        return f"fallback:{name}"

print(C().x)

Encapsulation Hard
A. hidden
B. AttributeError
C. None
D. fallback:x

46 What does the following code print?

PYTHON
class Base:
    @property
    def x(self):
        return 1

class Child(Base):
    x = 5

c = Child()
c.x = 9
print(c.x)

Encapsulation Hard
A. 1
B. 9
C. 5
D. AttributeError

47 What does Python print for this cooperative diamond hierarchy?

PYTHON
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())

Inheritance Hard
A. DBA
B. DBCA
C. DBAC
D. DCBA

48 What is the final trace produced by these cooperative initializers?

PYTHON
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)

Inheritance Hard
A. ['D', 'B', 'C', 'A']
B. ['A', 'B', 'C', 'D']
C. ['A', 'C', 'D', 'B']
D. ['A', 'C', 'B', 'D']

49 At which statement does Python first raise an exception?

PYTHON
class X:
    pass

class Y:
    pass

class A(X, Y):
    pass

class B(Y, X):
    pass

class C(A, B):
    pass

Inheritance Hard
A. At the definition of B
B. At the definition of A
C. At the definition of C
D. Only when creating C()

50 What does this class-method call return?

PYTHON
class A:
    @classmethod
    def who(cls):
        return cls.__name__

class B(A):
    @classmethod
    def who(cls):
        return super().who() + ":B"

print(B.who())

Inheritance Hard
A. B:A
B. A:B
C. A:A
D. B:B

51 What happens in this abstract-base-class example?

PYTHON
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())

Inheritance Hard
A. It prints B
B. Instantiation raises TypeError
C. It prints AB
D. It prints A

52 Which result correctly describes this virtual subclass registration?

PYTHON
from abc import ABC, abstractmethod

class Protocol(ABC):
    @abstractmethod
    def run(self):
        pass

class Worker:
    pass

Protocol.register(Worker)
w = Worker()

Inheritance Hard
A. isinstance(w, Protocol) is false, but w.run() returns None
B. isinstance(w, Protocol) is true, but w.run() raises AttributeError
C. isinstance(w, Protocol) is false, and w.run() raises AttributeError
D. isinstance(w, Protocol) is true, and w.run() returns None

53 What does this code print after mutation through one subclass and rebinding through another?

PYTHON
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)

Inheritance Hard
A. [] [1] [2]
B. [1] [1, 2] [1, 2]
C. [1] [1] [1, 2]
D. [1, 2] [1, 2] [1, 2]

54 Which special method handles the following addition?

PYTHON
class A:
    def __add__(self, other):
        return "A.__add__"

class B(A):
    def __radd__(self, other):
        return "B.__radd__"

print(A() + B())

OOP features Hard
A. B.__radd__
B. TypeError
C. A.__add__
D. B.__add__

55 What happens when hash(B()) is evaluated?

PYTHON
class A:
    def __hash__(self):
        return 7

class B(A):
    def __eq__(self, other):
        return True

OOP features Hard
A. It returns 7
B. It uses identity hashing
C. It returns True
D. It raises TypeError

56 What does this code print?

PYTHON
class C:
    def __len__(self):
        return 3

c = C()
c.__len__ = lambda: 9
print(len(c), c.__len__())

OOP features Hard
A. 3 3
B. 9 9
C. 9 3
D. 3 9

57 What is printed by this singleton-style implementation?

PYTHON
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)

OOP features Hard
A. False 1
B. False 2
C. True 1
D. True 2

58 After executing the setup below, which expression raises TypeError?

PYTHON
class C:
    def f(self, x):
        return x

c = C()
c.g = C.f

OOP features Hard
A. C.f(c, 3)
B. c.g(c, 3)
C. c.f(3)
D. c.g(3)

59 What happens when the copied method is called?

PYTHON
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())

Inheritance Hard
A. It raises AttributeError
B. It prints A
C. It prints AB
D. It raises TypeError

60 What does this descriptor example print?

PYTHON
class Label:
    def __get__(self, obj, owner):
        return "descriptor"

class C:
    x = Label()

c = C()
c.x = "instance"
print(c.x)

Encapsulation Hard
A. descriptor
B. None
C. AttributeError
D. instance