Tag: oops

Python- Abstract Class and Method

Abstract class are a blueprint for other classes and is considered as the class designer.

A class whn designed needs a concrete implementation. Abstract class hold a contract between a designer and the implementer.

Instance of Abstract class cannot be created and it needs to be inherited and implemented in the subclass.

For a larger functional unit or a generic/common functionlaity is to be provided use Abstract class. Abstract class allows to implement the fucntionlaity in the subclass.

Abstract method allows to declare the method and impelement the functionality in the subclasses where the Abstract class is inherited.

A method in class can be decorated/marked as abstract with @abstractmethod keyword. Use Import abc to use the Abstract method.

See below example of using Abstract method-

Here abc is imported and the print_output method is decorated as @abstractmethod. The definition of such method is pass which means a control is passed to the subclasses where a implementation is expected for printing based on the output device.

The print_out method is implemented in Printer and Console subclasses inherited from class having a abstract method.

TypeError

Python raises a TypeError if we try to instantitate a Abstract Class.

TypeError: Can’t instantiate abstract class OutputDevice with abstract method print_output

Python also raises error if the subclass doesn’t implement the abstract method in suclass.

See the below example for TypeErrors whilst using Abstract Class

Here the Log class does not implement the print_output abstract method.

You can also see the various usage of Static Methods, ClassMethods and there difference’s.

Add multiple constructor to Python Class

Python does not explicitly support multiple constructors in class. But there are ways you can provision a class with multiple constructors.

  1. Constructor Overloading using arguments
  2. Calling methods from constructors
  3. Using Class Method decorator

Constructor Overloading using arguments

Constructor overloading can be achieved using the same __init__ method and writing the functionality in the constructor method based on arguments.

See below example-

Calling methods from constructors

Same as above example the below example calls the method from the constructor based on the isntance of the argument.