SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Tony Gaddis
Chapter:
Inheritance
Exercise:
Algorithm Workbench
Question:2 | ISBN:9780132576376 | Edition: 2

Question

Look at the following class definitions:
class Plant:
def __init__(self, plant_type):
self.__plant_type = plant_type
def message(self):
print("I'm a plant.")
class Tree(Plant):
def __init__(self):
Plant.__init__(self, 'tree')
def message(self):
print("I'm a tree.")
Given these class definitions, what will the following statements display?
p = Plant('sapling')
t = Tree()
p.message()
t.message()

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

The result output of the given statements:

I'm a plant.
I'm a tree.

Explanation:

Consider the given class definition is create two classes, Plant and Tree, with inheritance between them.

Take first statement is as follows: 

p = Plant('sapling')
  • This statement creates an instance of the Plant class with the argument 'sapling' passed to the constructor.
  • The __init__ method initializes the __plant_type attribute of the p object with the value 'sapling'

Next, take another statement is as follows:

t = Tree()
  • This statement creates an instance of the Tree class.
  • Since the Tree class doesn't have its own constructor, it inherits the __init__ method from the Plant class. The __init__ method of Tree calls the __init__ method of Plant with the argument 'tree'.
  • This initializes the __plant_type attribute of the t object with the value 'tree'.

Next, take another statement is as follows:

p.message()
  • This statement calls the message method on the p object.
  • The message method of the Plant class is executed, which prints the message "I'm a plant.".

Next, take final statement is as follows:

t.message()
  • This statement calls the message method on the t object.
  • The message method of the Tree class is executed, which prints the message "I'm a tree.".

Therefore, the output of the given statements will be display result as:

I'm a plant.
I'm a tree.

 

 

0 0

Discussions

Post the discussion to improve the above solution.