Thursday, February 8, 2018

ABC (Abstract Base Classes)


By defining an abstract base class (ABC), you can define common API names for different sub-classes. It is useful to implement a maintainable class hierarchy.

For example:
  • You have a base class Device and sub-classes are Router, Switch, Server.
  • You can have common API names like enable_device, disable_device, reboot_device for all the sub-classes.
  • APIs can be implemented as per the device type but their names will be common.
ABC ensures that derived classes implement all methods from the base class.

Notes:
  • With ABC, instantiating base class is impossible.
  • If you forget to implement abstract methods in sub-classes, it will raise an error as early as possible.

Example:
from abc import ABCMeta, abstractmethod

class Animal(object):
    __metaclass__ = ABCMeta   # python 2.7

    @abstractmethod
    def name(self):
        raise NotImlpementedError()

    @abstractmethod
    def color(self):
        raise NotImlpementedError()

class Cat(Animal):
    def name(self):
        print "My name is cat"

    def color(self):
        print "My color is white"

# If you forget to implement abstract methods (name/color) in class Cat, you will get following error:
TypeError: Can't instantiate abstract class Cat with abstract methods <name/color>

# You can't instantiate base class Animal, if you try to do so, you will get following error:
>>> a = Animal()
TypeError: Can't instantiate abstract class Animal with abstract methods name, color

# You can instantiate derived class Cat, and call its methods
>>> d = Cat()
>>> d.name()
My name is cat
>>> d.color()
My color is white


No comments:

Post a Comment