idioms for abstract base classes

Steve Purcell stephen_purcell at yahoo.com
Fri Apr 13 07:29:41 EDT 2001


Robin Becker wrote:
> what's the best way to spell an abstract base class so that
> 0) base is B and A inherits from B
> 
> 1) doing B() causes an exception
> 
> 2) most of the initialisation code is common in B


It's not often worth trying to enforce abstractness, but the following
might work for you:


    >>> class B:
    ...   def __init__(self, *args, **kw):
    ...      if self.__class__ is B: raise "B is abstract"
    ...      self.args = args
    ... 
    >>> B()
    Traceback (innermost last):
      File "<stdin>", line 1, in ?
      File "<stdin>", line 3, in __init__
    B is abstract
    >>> class A(B):
    ...    pass
    ... 
    >>> a = A(1,2,3)
    >>> a.args
    (1, 2, 3)
    >>> 


-Steve

-- 
Steve Purcell, Pythangelist
Get testing at http://pyunit.sourceforge.net/
Any opinions expressed herein are my own and not necessarily those of Yahoo




More information about the Python-list mailing list