Python MCQs - OOP and Exception Handling (Set 5)

Python MCQs - OOP and Exception Handling (Set 5) - CodingHumans

This set tests object-oriented programming and error handling in Python. Questions cover class versus instance attributes, inheritance and the method resolution order in diamond hierarchies, cooperative super() calls, dunder methods such as __str__, __repr__, __eq__, __len__ and __radd__, properties, name mangling, abstract base classes, and the flow of try, except, else and finally including custom exceptions. Expect these in Python developer interviews, placement tests and university OOP examinations.

How to practise: read each question and tap the option you think is correct. You will see right away whether you got it, along with a short explanation, and your score is tracked at the bottom of the screen. This set has 18 questions.

Python MCQ series: Set 1 | Set 2 | Set 3 | Set 4 | Set 5 | Set 6

Topics covered in this set

  • Class attributes vs instance attributes
  • Inheritance, MRO and super()
  • Dunder methods and operator overloading
  • Properties, name mangling and abstract classes
  • try, except, else and finally flow
  • Exception hierarchy and custom exceptions

Python MCQs with answers and explanations

Q1. What is the output of the following code?

class A:
    items = []

a = A()
b = A()
a.items.append(1)
print(b.items)

a) []

b) [1]

c) AttributeError

d) None

Q2. What is the output of the following code?

class A:
    n = 0
    def __init__(self):
        self.n += 1

a = A()
b = A()
print(A.n, a.n)

a) 2 2

b) 0 1

c) 2 1

d) 0 2

Q3. What is the output of the following code?

class A:
    def f(self): return "A"
class B(A):
    def f(self): return "B"
class C(A):
    def f(self): return "C"
class D(B, C):
    pass

print(D().f(), D.__mro__[2].__name__)

a) C B

b) B A

c) A C

d) B C

Q4. What is the output of the following code?

class A:
    def __init__(self):
        print("A", end="")
class B(A):
    def __init__(self):
        print("B", end="")
        super().__init__()
class C(A):
    def __init__(self):
        print("C", end="")
        super().__init__()
class D(B, C):
    def __init__(self):
        print("D", end="")
        super().__init__()

D()

a) DBCA

b) DBA

c) DBACA

d) DCBA

Q5. What is the output of the following code?

def f():
    try:
        return 1
    finally:
        return 2

print(f())

a) 1

b) SyntaxError

c) None

d) 2

Q6. What is the output of the following code?

try:
    print("a", end="")
    x = 1 / 0
except ZeroDivisionError:
    print("b", end="")
else:
    print("c", end="")
finally:
    print("d", end="")

a) abcd

b) ad

c) abd

d) acd

Q7. What is the output of the following code?

class P:
    def __repr__(self): return "R"
    def __str__(self): return "S"

p = P()
print(p, [p], f"{p!r}")

a) S [S] R

b) S [R] R

c) R [R] R

d) S [S] S

Q8. What is the output of the following code?

class K:
    def __eq__(self, other):
        return True

print(len({K(), K()}))

a) 1

b) 2

c) TypeError

d) 0

Q9. What is the output of the following code?

class C:
    def __len__(self):
        return 0

print(bool(C()), "yes" if C() else "no")

a) True yes

b) False yes

c) False no

d) TypeError

Q10. What is the output of the following code?

try:
    int("x")
except Exception:
    print("E")
except ValueError:
    print("V")

a) V

b) E V

c) E

d) SyntaxError

Q11. What does a method decorated with @classmethod receive as its first argument?

a) The instance on which it was called

b) The class on which it was called

c) Nothing; it receives no implicit argument

d) The module where the class is defined

Q12. What is the output of the following code?

class A:
    def __init__(self):
        self.__x = 5

a = A()
print(hasattr(a, '__x'), a._A__x)

a) True 5

b) False 5

c) False AttributeError

d) True None

Q13. What is the output of the following code?

class MyErr(ValueError):
    pass

try:
    raise MyErr("bad")
except ValueError as e:
    print(type(e).__name__, e)

a) MyErr bad

b) ValueError bad

c) MyErr MyErr('bad')

d) ValueError MyErr

Q14. What is the output of the following code?

class V:
    def __init__(self, n): self.n = n
    def __add__(self, o): return V(self.n + o)
    def __radd__(self, o): return V(self.n + o + 100)

print((V(1) + 2).n, (2 + V(1)).n)

a) 3 103

b) 3 3

c) 103 3

d) TypeError

Q15. What is the output of the following code?

print(isinstance(True, int), issubclass(bool, object), isinstance(3, float))

a) True True False

b) False True False

c) True False False

d) True True True

Q16. KeyboardInterrupt and SystemExit derive directly from which class?

a) BaseException

b) Exception

c) RuntimeError

d) object

Q17. What is the output of the following code?

class T:
    def __init__(self):
        self._c = 0
    @property
    def c(self):
        return self._c

t = T()
t.c = 5
print(t.c)

a) 5

b) 0

c) TypeError

d) AttributeError

Q18. What is the output of the following code?

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self): ...

class Square(Shape):
    pass

Square()

a) NotImplementedError

b) AttributeError

c) No output; the object is created

d) TypeError

Quick revision notes

  • Class attributes are shared by all instances; assigning via self creates an instance attribute.
  • MRO uses C3 linearisation; inspect it with ClassName.__mro__ or ClassName.mro().
  • super() follows the MRO of the instance's class, not simply the parent class.
  • print() uses __str__; containers and !r use __repr__.
  • Defining __eq__ without __hash__ makes instances unhashable.
  • Only the first matching except clause runs, so put specific exceptions before general ones.
  • else runs only when no exception occurred; finally always runs, and a return in finally overrides others.
  • BaseException is the root; Exception is the base for ordinary errors.

Frequently asked questions

What is MRO in Python?

The Method Resolution Order is the sequence of classes Python searches when looking up an attribute. It is computed with the C3 linearisation algorithm, which keeps children before parents and respects the order of base classes.

What is the difference between __str__ and __repr__?

__str__ gives a readable string for end users and is used by print() and str(). __repr__ gives an unambiguous, developer-oriented representation and is used in the interpreter, inside containers and as a fallback when __str__ is missing.

When does the else block of a try statement run?

The else block runs only if the try block finishes without raising an exception. It is useful for code that should run on success but whose own errors should not be caught by the preceding except clauses.

Comments

Answered 0/0Correct 0