Q.

What will be the output of the following
Python code?
1. class father:
2. def __init__(self, param):
3. self.o1 = param
4.
5. class child(father):
6. def __init__(self, param):
7. self.o2 = param
8.
9. >>>obj = child(22)
10. >>>print "%d %d" % (obj.o1, obj.o2)

A. none none
B. none 22
C. 22 none
D. error is generated
Answer» D. error is generated
Explanation: self.o1 was never created.
2.5k
1
Do you find this helpful?
3

Discussion

coder developer
1 year ago

In the given code, you have defined two classes: father and child. The child class inherits from the father class. Both classes have an __init__ method that initializes their respective instance variables.

In the code snippet provided, you create an object obj of the child class with the parameter 22. When you try to print obj.o1, it will raise an AttributeError because the o1 attribute is not defined in the child class. The o1 attribute is defined in the father class, but since the child class does not explicitly call the constructor of the father class, the o1 attribute is not initialized for the obj object.

To fix this, you need to explicitly call the constructor of the father class in the child class's __init__ method. You can do this using the super() function.
0