Examveda

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

A. Parent method

B. An error will occur

C. Child method

D. obj

Answer: Option A

Solution (By Examveda Team)

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".

This Question Belongs to Python Program >> Classes And Objects In Python

Join The Discussion

Comments (1)

  1. Muhammad Sharif
    Muhammad Sharif:
    4 months ago

    Wrong correct option is A.

    I have tested the code by running it.

Related Questions on Classes and Objects in Python