My blog has moved!

You should be automatically redirected. If not, visit
http://benohead.com
and update your bookmarks.

Tuesday, April 24, 2012

Abstract classes in python

Abstract classes (or abstract types) are a common concept in object-oriented programming. They cannot be instantiated and may contain methods without implementation (called abstract methods). In order to be used, they need to be derived to concrete classes (which fully implement all methods defined in the parent abstract class). Interfaces are also very similar to abstract classes without any implementation (although they are different from a sementical point of view).

Python has neither abstract classes nor interfaces. But there is a couple of ways to replicate this behavior:

A class can define "placeholder" methods which do nothing (pass):

class AbstractClass(object):
    def abstractMethod(self):
        pass


The issue with this way of defining an abstract class is that this class can be instantiated and the method can be called (but will have no effect).

In order to make sure that this class cannot be instantiated, you can implement some login in __init__:

def __init__(self):
    if type(self) == AbstractClass:
        raise Exception("AbstractClass is an abstract class and cannot be instantiated.")


And in order to make sure that the empty methods cannot be called, you can raise an exception instead of passing:

def abstractMethod(self):
        raise NotImplementedError


These two checks are of course not providing the same as abstract classes in other languages since the check will only be performed at runtime and not at compile time.

No comments:

Post a Comment