Vidyalelo
Python · Q30

Classes and Objects in Python

Programming · Python · question 30

Q30

What is the output of the following code:class Parent: def show(self): print('Parent method')class Child(Parent): passobj = Child()obj.show()

A.
Parent method
Answer
B.
An error will occur
C.
Child method
D.
obj

Answer: Option A

Solution

Answer: Option A
Solution:
The correct answer is A: Parent method

Here's why:

We have a class called `Parent` that has a method named `show`. This method prints "Parent method".

Then, we create another class called `Child` that inherits from the `Parent` class. This means the `Child` class automatically gets all the methods and attributes of the `Parent` class.

Importantly, the `Child` class doesn't define its own `show` method. It inherits the `show` method directly from `Parent`.

We create an object of the `Child` class called `obj`.

When we call `obj.show()`, Python looks for a `show` method in the `Child` class. Since it doesn't find one there, it looks in the `Parent` class (because `Child` inherits from `Parent`).

It finds the `show` method in the `Parent` class and executes it. Therefore, it prints "Parent method".