Python Abstract Classes vs Interfaces

Python does not provide interface concept explicitly. It provides abstract classes which can be used as either abstract classes or interfaces. It is the discretion of the programmer to decide when to use an abstract class and when to go for an interface. Generally, abstract class is written when there are some common features shared by all the objects as they are.


Summary


  • An abstract method is a method whose action is redefined in the sub classes as per the requirement of the objects.

  • Generally, an abstract method is written without any body. But it is possible to write an abstract method with body also.

  • A method with body is called concrete method.

  • An abstract class is a class that contains some abstract methods. An abstract class can also contain concrete methods.

  • Abstract methods are written with a decorator @abstractmethod above them.

  • It is not possible to create an object (or instance) to an abstract class.

  • Every abstract class should derive from ABC class that is available in abc (abstract base class) module.

  • All the abstract methods of the abstract class should be rewritten with body in the sub classes.That means the abstract methods should be overridden in the sub classes.

  • We can create objects (or instances) to sub classes.

  • If a sub class does not implement all the methods of the abstract super class, then that sub class should also be declared as abstract class and an object to that sub class cannot be created.

  • An abstract class can perform various tasks through various implementations of its methods in the sub classes.

  • An abstract class will become an interface when it contains only abstract methods and there are no concrete methods.

  • It is not possible to create objects (or instances) to interfaces.

  • All the methods of the interface should be implemented in its sub classes.

  • The built-in function globals()[str] converts the string 'str' into a classname and returns the classname.

  • An abstract class is written when there are some common features shared by all the objects.

  • An interface is written when all the features are implemented differently for different objects.

  • When an interface is written, any third party vendor can provide sub classes.

  • Both the abstract classes and interfaces are examples for polymorphism.