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:
Checkpoint
Question:5 | ISBN:9780132576376 | Edition: 2

Question

Look at the following class definitions:
class Vegetable:
    def __init__(self, vegtype):
         self.__vegtype = vegtype
    def message(self):
         print("I'm a vegetable.")
class Potato(Vegetable):
    def __init__(self):
         Vegetable.__init__(self, 'potato')
    def message(self):
         print("I'm a potato.")
Given these class definitions, what will the following statements display?
v = Vegetable('veggie')
p = Potato()
v.message()
p.message()

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

The output of the given code is as follows:

I'm a vegetable.
I'm a potato.

Explanation:

  • v = Vegetable('veggie'): This creates an instance of the Vegetable class with the vegtype attribute set to 'veggie'.
  • p = Potato(): This creates an instance of the Potato class. Since Potato is a subclass of Vegetable, the __init__ method of Potato calls the __init__ method of the parent class Vegetable and passes 'potato' as the vegtype argument.
  • v.message(): This calls the message() method on the v instance of Vegetable. The message() method of the Vegetable class is executed, which prints "I'm a vegetable."
  • p.message(): This calls the message() method on the p instance of Potato. Since Potato is a subclass of Vegetable and has its own message() method, the message() method of the Potato class is executed, which prints "I'm a potato.

Finally, the output of the given statements will be "I'm a vegetable." and "I'm a potato." respectively.

0 0

Discussions

Post the discussion to improve the above solution.