Object Oriented

Interface

Python

 

Interface (Python 2)

Python 2.7
from abc import ABCMeta, abstractmethod

class myInterface:
  __metaclass__ = ABCMeta

  @abstractmethod
  def myAbstractMethod(self):
    pass

Interface is a tool to achieve better abstraction.

Interface specifies a list of methods that Classes should implement.

Python doesn't natively support interfaces.

You define abstract classes using abc module and since Python supports multi-class inheritance, you can mimic interfaces.

Here we are mimicking interface myInterface in Python2.

We're going to explain how to mimic interfaces in Python3 on the next card.

 

Interface (Python 3)

Python 3.7
from abc import ABCMeta, abstractmethod

class myInterface(metaclass=ABCMeta):
  
    @abstractmethod
    def myAbstractMethod(self):
        pass

In order to mimic Interfaces in Python3, we're using a similar approach to what we did in Python2, with a slightly different syntax.

 

Abstract Class (Python 2)

Python 2.7
from abc import ABCMeta, abstractmethod

class Teacher:
  __metaclass__ = ABCMeta
  
  def greet(self):
    print("Hello Students!");
  
  @abstractmethod
  def work(self):
    pass


class PhysicsTeacher(Teacher):
  def work(self):
    print("I'm teaching physics!")

Abstract Class can have abstract methods.

Abstract Method is a method without an implementation.

Python doesn't natively support abstract classes.

The abc module provides us with tools to have abstract class and method behaviors in Python.

Here we are mimicking an Abstract Class Teacher in Python2.

We're going to explain how to mimic interfaces in Python3 in the next card.

 

Abstract Class (Python 3)

Python 3.7
from abc import ABCMeta, abstractmethod

class Teacher(metaclass=ABCMeta):
  
  def greet(self):
    print("Hello Students!");
  
  @abstractmethod
  def work(self):
    pass


class PhysicsTeacher(Teacher):
  def work(self):
    print("I'm teaching physics!")

In order to mimic Interfaces in Python3, we're using a similar approach to what we did in Python2, with a slightly different syntax.