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


Difference between == and is


  • == (Equality)
    • Take an example of identical twins. Look wise they are exactly same (equal).
    • Expression evaluates to True if two objects (referred by variables) have the same contents (or are equal).
  • is (Identity)
    • Take an example of identical twins. Both are different human beings.
    • Expression evaluates to True if two variables point to the same (identical) object.

>>> a = [1,2,3]
>>> id(a)
4557217944
>>> b = a
>>> id(b)
4557217944

>>> a == b
True
>>> a is b
True

Note: Here a is a list, which has a particular identity (4557217944), and we are assigning a to b, so b has the same identity as a (4557217944).

>>> a = [1,2,3]
>>> id(a)
4557293400
>>> b = [1,2,3]
>>> id(b)
4557140408

>>> a == b
True
>>> a is b
False

Note: Here a is a list, which has a particular identity (4557293400), and we are creating a new list b, so b has a different identity (4557140408) than a's identity (4557293400).