Abstract class

Maric Michaud maric at aristote.info
Mon Sep 15 08:09:13 EDT 2008


Le Sunday 14 September 2008 22:25:18 Steven D'Aprano, vous avez écrit :
> 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
>
>

But this doesn't match what abstract classes are (in C++ for example), because 
__init__ can, and probably will, have logic reusable in concrete classes. The 
only way to do this is to call in the __int__ at least one of the methods 
raising NotImplementedError, probably creating a dummy one for this purpose, 
and still it doesn't satisfy with the constraint that *all* abstract methods 
must be implemented in concrete classes.

> "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?

I agree with you on this, and the simple scheme of defining some methods 
raising exceptions is obviously sufficiient where duck typing is.

ABC, as I understood it, is for resolving another problem : unrelated (by 
inheritance) classes, which share the same signature, but need to be 
distinguished in their behavior.

-- 
_____________

Maric Michaud




More information about the Python-list mailing list