44.
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
(Python Question) Which class do you belong?**
What is the output of the following piece of code?
class A:
def __init__(self):
self.__i = 1
self.j = 5
def display(self):
print(self.__i, self.j)
class B(A):
def __init__(self):
super().__init__()
self.__i = 2
self.j = 7
c = B()
Show answer & explanation
Answer: A. 1 7
Name mangling in Python prefixes __i with the class name. In class A, self.__i becomes _A__i. When B's __init__ assigns self.__i = 2, it creates a new attribute _B__i (not the parent's _A__i). Since display() is defined in A and accesses self.__i, it reads _A__i which remains 1. However, self.j is public and gets overwritten by B's assignment to 7. Output: 1 7
Step-by-step Derivation:
- B() calls B.init()
- super().init() calls A.init(), setting self._A__i = 1 and self.j = 5
- self.__i = 2 in B's context creates self._B__i = 2 (name mangling: __i → _B__i in class B)
- self.j = 7 overwrites the public attribute to 7
- c.display() calls A's display() method
- A's display() accesses self.__i, which due to name mangling in A's context reads self._A__i = 1 (not _B__i)
- self.j = 7 (the public attribute)
- Output: 1 7