Sunday, February 6, 2011

Creating Abstract Class in Python

Prior to Python 2.6, Python had no concept of abstract class. To enforce that a derived class implements some particular methods from the base class, we can do something like this.
class BaseClass:
    def do_something(self):
        assert False, "Not implemented"

class DerivedClass(BaseClass):
    def do_mystuff(self):
        print "Do my stuff!"
    def do_something(self):
        print "Do something!"
        
if __name__ == "__main__":
    c = DerivedClass()
    c.do_something()
    c.do_mystuff()
If we don't implement the do_something() method, an exception will be raised.

In Python 2.6 onwards, we can achieve the same functionality in a more elegant manner with the help from abc (Abstract Base Class) module.

from abc import ABCMeta, abstractmethod

class BaseClass:
    __metaclass__ = ABCMeta

    @abstractmethod
    def do_something(self): pass

class DerivedClass(BaseClass):
    def do_mystuff(self):
        print "Do my stuff!"
    def do_something(self):
        print "Do something!"
        
if __name__ == "__main__":
    c = DerivedClass()
    c.do_something()
    c.do_mystuff()

No comments:

Post a Comment