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()
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')
Plant
class with the argument 'sapling'
passed to the constructor.__init__
method initializes the __plant_type
attribute of the p
object with the value 'sapling'
Next, take another statement is as follows:
t = Tree()
Tree
class.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'
.__plant_type
attribute of the t
object with the value 'tree'
.Next, take another statement is as follows:
p.message()
message
method on the p
object.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()
message
method on the t
object.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.