Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's super(), abstract base classes, and NotImplementedError

Abstract base classes can still be handy in Python. In writing an abstract base class where I want every subclass to have, say, a spam() method, I want to write something like this:

class Abstract(object):
    def spam(self):
        raise NotImplementedError

The challenge comes in also wanting to use super(), and to do it properly by including it in the entire chain of subclasses. In this case, it seems I have to wrap every super call like the following:

class Useful(Abstract):
    def spam(self):
        try:
            super(Useful, self).spam()
        except NotImplementedError, e:
            pass
        print("It's okay.")

That's okay for a simple subclass, but when writing a class that has many methods, the try-except thing gets a bit cumbersome, and a bit ugly. Is there a more elegant way of subclassing from abstract base classes? Am I just Doing It Wrong?

like image 631
gotgenes Avatar asked Jan 25 '11 22:01

gotgenes


1 Answers

You can do this cleanly in python 2.6+ with the abc module:

import abc
class B(object):
    __metaclass__ = abc.ABCMeta
    @abc.abstractmethod
    def foo(self):
        print 'In B'

class C(B):
    def foo(self):
        super(C, self).foo()
        print 'In C'

C().foo()

The output will be

In B
In C
like image 106
Sam Dolan Avatar answered Oct 13 '22 23:10

Sam Dolan