Abstract class

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Sep 14 22:25:18 CEST 2008


On Sun, 14 Sep 2008 12:15:04 -0700, Gary Herron wrote:

> (If you wish to consider the base class "abstract", just agree with
> yourself to not instantiate it.)

That's certainly the most lightweight option.

 
> Please forget about Abstract Base Classes.  They have nothing to do with
> what you want, and are a *HUGE* overkill for your application.   They
> are not (yet) even part of standard Python, and are used primarily for a
> class implementor to guarantee  to a user of a class that it provides a
> specific interface.


You can implement a lightweight abstract base class in Python fairly 
easily, by adding two lines to the __init__ method of your base class.


class Base(object):
    def __init__(self):
        if self.__class__ is Base:
            raise NotImplementedError("Abstract base class")
    def method(self, *args):
        return len(args)  # or something useful


If you want to get fancy, you can define a custom exception instead of 
using NotImplementedError. And that's about all you need. You can get 
more complicated if you want, but why bother?

If I may be excused a slight digression, I don't get the "abstract" part 
of ABCs. The prohibition against instantiating them just seems very 
artificial, I don't see what benefit it gets you. Wikipedia says:

"The fact that many languages disallow instantiation of abstract types 
(and force subtypes to implement all needed functionality) further 
ensures program correctness."

http://en.wikipedia.org/wiki/Abstract_base_class

but I don't see how that follows (except possibly in very special cases). 
Given that the set of instances of class B is empty, how does that help 
you know that B.method is correct?



-- 
Steven



More information about the Python-list mailing list