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 module for importing packages
B. A blueprint for creating objects
C. A loop for repeating statements
D. A condition for selecting statements

2 What is an object in object-oriented programming?

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

3 Which special method commonly initializes a new Python object?

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

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

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

5 What is a method in a Python class?

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

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

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

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. Converting values into one type
B. Importing functions from one module
C. Bundling data and methods in one class
D. Repeating statements within one loop

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 underscore
C. A single trailing underscore
D. A single leading asterisk

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

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

11 What is the usual purpose of a getter method?

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

12 What is the usual purpose of a setter method?

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

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 loop
D. A module

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

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

15 What does inheritance allow a Python class to do?

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

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

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

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

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

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

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

19 What is method overriding?

Inheritance Easy
A. Redefining a parent method in a child class
B. Importing a method from another module
C. Deleting a method from every class
D. Calling a child method from a parent 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 objects created from one class
D. Several attributes sharing one value

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. 100 100
B. 150 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. ['Woof', 'Meow']
B. ['Meow', 'Woof']
C. ['Woof', 'Woof']
D. ['Meow', '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. Method overriding
B. Composition
C. Data abstraction
D. Inheritance

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. __init__()
B. __call__()
C. __str__()
D. __new__()

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. Class shadowing
B. Constructor chaining
C. Duck typing
D. Name mangling

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. A TypeError is raised
B. A warning is printed
C. The abstract method returns None
D. An empty object is created

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. A NameError is raised
C. None is printed normally
D. An AttributeError 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. An AttributeError is raised
B. The price remains 50 silently
C. The price becomes -20
D. A ValueError is raised

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

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

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. An AttributeError is raised
B. The assignment is ignored
C. A new property is created
D. The value changes to 30

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. safe False
C. None True
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. BaseChild
B. Base
C. None
D. Child

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. ['pen']
C. []
D. An AttributeError

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. An AttributeError
B. Asha 9
C. None 9
D. Asha None

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. C
B. PC
C. CP
D. P

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. B A C
B. C B A
C. B C A
D. A B 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 8
C. 8 8
D. 5 5

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. True False False
B. False True True
C. True True True
D. True True 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 Child
B. Child Base
C. Base Base
D. Base Child

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] False
B. [] [] False
C. [1] [1] True
D. [1] [] True

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. B
B. A
C. AB
D. AttributeError

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. 2 2
B. AttributeError
C. 1 2
D. 1 1

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. 10 99
B. AttributeError
C. 10 10
D. 99 99

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. None
C. fallback:x
D. AttributeError

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. AttributeError
B. 9
C. 5
D. 1

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. DCBA
B. DBCA
C. DBAC
D. DBA

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. ['A', 'C', 'D', 'B']
B. ['D', 'B', 'C', 'A']
C. ['A', 'B', 'C', 'D']
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 A
B. Only when creating C()
C. At the definition of B
D. At the definition of 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:B
B. B:A
C. A:A
D. A: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 A
B. It prints AB
C. Instantiation raises TypeError
D. It prints B

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, and w.run() returns None
C. isinstance(w, Protocol) is false, and w.run() raises AttributeError
D. 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?

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] [1] [1, 2]
B. [1, 2] [1, 2] [1, 2]
C. [1] [1, 2] [1, 2]
D. [] [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.__add__
B. B.__radd__
C. A.__add__
D. TypeError

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 True
B. It uses identity hashing
C. It returns 7
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 3
C. 3 9
D. 9 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 2
B. False 1
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.g(3)
B. c.f(3)
C. c.g(c, 3)
D. C.f(c, 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 prints AB
B. It prints A
C. It raises TypeError
D. It raises AttributeError

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. None
B. AttributeError
C. instance
D. descriptor