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:3 | ISBN:9780132576376 | Edition: 2

Question

Look at the following class definition:
class Beverage:
        def __init__(self, bev_name):
              self.__bev_name = bev_name
Write the code for a class named Cola that is a subclass of the Beverage class. The
Cola class’s __init__ method should call the Beverage class’s __init__ method,passing ‘cola’ as an argument.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

# Beverage class definition
class Beverage:
    def __init__(self, bev_name):
        self.__bev_name = bev_name

# Cola class definition, subclass of Beverage
class Cola(Beverage):
    def __init__(self):
        # Call the superclass (Beverage) constructor using super()
        # Pass 'cola' as an argument to the Beverage class's __init__ method
        super().__init__('cola')

# Create an instance of the Cola class and demonstrate its usage
def main():
    # Create a Cola object
    cola = Cola()

    # Access the beverage name attribute using the superclass (Beverage) accessor method
    print("Beverage Name:", cola._Beverage__bev_name)

# Call the main function to start the program
if __name__ == "__main__":
    main()

Executed Output:

Beverage Name: cola

 

0 0

Discussions

Post the discussion to improve the above solution.