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()
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.