February 8, 2021

Abstract Class in Python With Examples

In this tutorial you will learn about Abstract class which is an important concept in object oriented programming and how to define abstract classes in Python using abc module.

What is an Abstract class

An abstract class is a class that contains one or more abstract methods. Abstract methods are methods without any body so a sub-class that extends the abstract class has to provide implementation for the abstract methods.

Creating Abstract class in Python

Abstract class in Python is created by extending the ABC meta class which is the part of abc (Abstract Base Class) module.

from abc import ABC
Class MyClass(ABC):

Abstract method in Python

Abstract method is a method that is annotated with @abstractmethod decorator. Decorator @abstractmethod has to be imported from abc module.

Syntax of Abstract class with an abstract method

from abc import ABC, abstractmethod
Class MyClass(ABC):
 @abstractmethod
 def mymethod(self):
  pass

Why use an Abstract class

Using Abstract class helps in reducing code duplication. You can create a hierarchical structure where parent class (which is defined as an abstract class) contains implementation of the methods which are going to be common for the child classes and leave what may differ as abstract methods. When child classes extend the parent class they can implement the abstract methods as per their required functionality.

Abstract class Python example

Suppose you have to design payment functionality where you have to provide functionality for cash and credit card payment and you need to capture customer details like name, address.

Here capturing customer details is common but the mode of payment is different. In this scenario you can create an abstract class with abstract doPayment() method which has to be implemented by the sub classes and keep the functionality to capture and print customer details as a concrete method in abstract class to be used by all the sub classes.

from abc import ABC, abstractmethod

class Payment(ABC):
  def __init__(self, customer_name, customer_address):
    self.customer_name = customer_name
    self.customer_address = customer_address

  def print_customer_info(self):
    print('Customer Name:', self.customer_name)
    print('Customer Address:', self.customer_address)

  @abstractmethod
  def do_payment(self, amount):
    pass

class CreditPayment(Payment):
  def __init__(self, customer_name, customer_address):
    super().__init__(customer_name, customer_address)

  def do_payment(self, amount):
    print('In child class CreditPayment, payment of-', amount)
    super().print_customer_info()

class CashPayment(Payment):
  def __init__(self, customer_name, customer_address):
    super().__init__(customer_name, customer_address)

  def do_payment(self, amount):
    print('In child class CashPayment, payment of-', amount)
    super().print_customer_info()


# object of Child class
obj = CreditPayment("Ryan", "5th ave, NYC")
obj.do_payment(34.56)
obj = CashPayment("Nina", "Burnsville, NC")
obj.do_payment(12.23)
Output
In child class CreditPayment, payment of- 34.56
Customer Name: Ryan
Customer Address: 5th ave, NYC
In child class CashPayment, payment of- 12.23
Customer Name: Nina
Customer Address: Burnsville, NC

In the example Abstract class Payment has one concrete methods print_customer_info() that is invoked from the child classes using the super() function.

Important points about Python Abstract class

Some of the important features of abstract class in Python are as following-

  1. Abstract class may contain both concrete methods as well as abstract methods. We have already seen that in the above example.
  2. Since abstract class doesn’t contain the full functionality so you can’t instantiate an abstract class. In the above example trying to create an object of Payment class (obj = Payment("Ram", "Pink street, Jaipur")) which is abstract results in an error-
        obj = Payment("Ram", "Pink street, Jaipur")
    TypeError: Can't instantiate abstract class Payment with abstract methods do_payment
    
  3. Subclass that extends the abstract class must implement all the abstract methods of the abstract class. If we have a definition as following where CashPayment class doesn’t implement the abstract method do_payment() of the parent class.
    class CashPayment(Payment):
        def __init__(self, customer_name, customer_address):
            super().__init__(customer_name, customer_address)
    
    This results in error
    obj = CashPayment("Nina", "Burnsville, NC")
    TypeError: Can't instantiate abstract class CashPayment with abstract methods do_payment
    

That's all for the topic Abstract Class in Python With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment