Ads by ProfitSence
Close

Python Abstract Class

Last Updated on Wednesday 5th Oct 2022
  • Python is a semi-OOP language that has several OOP features.
  • While python cannot enforce the interface of a class, it can create an abstract class to enforce rigidity while building a subclass.
			
					from abc import ABC, abstractmethod

			
	
  • ABC stands for the abstract base class. Any class that we want to enforce using abstract class should inherit from ABC.
  • Abstractmethod is a decorator for a class method that the function will become apparent soon.
			
					from abc import ABC, abstractmethod

class AbstractExample(ABC):
    @abstractmethod
    def do(self):
        print("Hello Alice")

class AnotherSub(AbstractExample):
    def do(self):
        super().do()
        print("What are you Doing?")

x = AnotherSub()
x.do()

			
	

It Outputs

			
					# Hello Alice
# What are you Doing?

			
	

python abc

			
					from abc import ABC, abstractmethod

class AbstractExample(ABC):
    def __init__(self, init_val):
        self.init_val = init_val

    @abstractmethod
    def action(self):
        pass

class ConcereteExampleWithMethod(AbstractExample):
    def __init__(self, init_val):
        super().__init__(init_val)

    def action(self):
        print(self.init_val)

cewm = ConcereteExampleWithMethod(88)
cewm.action()

			
	

It Outputs

			
					# 88

			
	
  • We successfully initiate ConcreteExampleWithMethod class when inheriting from AbstractExample.
  • An abstract class should inherit from ABC; otherwise, it won't enforce the abstract decorator method.