📅  最后修改于: 2023-12-03 15:42:11.432000             🧑  作者: Mango
This is a question asked in the GATE (Graduate Aptitude Test in Engineering) for Computer Science in the year 2011.
Consider the following code:
class A:
def __init__(self, i = 0):
self.i = i
class B(A):
def __init__(self, j = 0):
self.j = j
def main():
b=B()
How can method main()
of class B
be corrected to properly initialize an object of class B
?
(A) Add A.__init__(self)
at the beginning of B.__init__(self, j = 0)
.
(B) Add A.__init__(self)
at the end of B.__init__(self, j = 0)
.
(C) Add A.__init__(self)
at the beginning of method main()
.
(D) Add A.__init__(i, self)
at the beginning of B.__init__(self, j = 0)
.
(B)
While creating an object of class B
, the constructor of class A
is not called automatically. Hence, the instance variable i
of class A
is not initialized.
To initialize the instance variable i
of class A
, we need to explicitly call the constructor of class A
from the constructor of class B
. We can achieve this by calling A.__init__(self)
in the constructor of class B
.
Therefore, the correct way of initializing an object of class B
is to add A.__init__(self)
at the end of B.__init__(self, j = 0)
.
class A:
def __init__(self, i = 0):
self.i = i
class B(A):
def __init__(self, j = 0):
self.j = j
A.__init__(self)
def main():
b=B()
Hence, option (B) is the correct answer.