Python program From the given class definitions class Plant

Python program: From the given 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.\") What will the following statements display? Explain?

Solution

Output:

Consider the class definitions given below:

p = Plant (‘sapling’)

t = Tree ( )

P.message ( )

t.message ( )

The output of the given class definitions and code is:

I’ a plant

I’m a tree.

In the given code there are two classes – Plant and Tree. The class Tree is a subclass of Plant which means that Tree IS-A Plant. The two objects are declared.

p = Plant (‘sapling’)

t = Tree ( )

Object p is a Plant and t is a Tree. Thus, according to the rules of polymorphism when the method message ( ) is called upon p, then the method from class Plant is called and when the same method is called upon t, then the method from class Tree is called.

This happens because the method or super class is overridden by the method of subclass and Tree class overrides the message ( ) method from Plant class.

 Python program: From the given class definitions class Plant: def_init_(self, plant_type): self.plant_type = plant_type def message(self): print(\

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site