Question 27: Understanding Abstract Methods In Python

This Python quiz question tests your understanding of abstract base classes and abstract methods in python.

Question: Abstract Methods In Python

What will be the output of the following code?

from abc import ABC, abstractmethod

class Enterprise (ABC): 
    @abstractmethod
    def calcYear Expenses():
        pass
        
class TechShop (Enterprise):
    def _init__(self):
        print("TechShop")
        
obj = TechShop()















Answer: B

Explanation:

Abstract classes are classes that cannot be instantiated directly and are meant to be subclassed.

They often contain abstract methods, which are methods declared but contain no implementation. Subclasses must provide an implementation for these methods.

Enterprise is an abstract class that inherits from ABC.

The method calcYearExpenses() is defined as an abstract method using the @abstractmethod decorator.

This means any subclass of Enterprise must implement this method.

TechShop is a subclass of Enterprise. However, there is an issue here:

  • The calcYearExpenses() method is not implemented in the TechShop class.
  • Since it’s an abstract method in the parent class, TechShop must implement it, or else it can’t be instantiated.

Leave a Reply