Abstract Classes

Rhodri James rhodri at wildebst.demon.co.uk
Sat May 23 23:59:47 CEST 2009


On Sat, 23 May 2009 12:02:00 +0100, Tim Cook <timothywayne.cook at gmail.com>  
wrote:

> I am implementing a set of specifications that were designed to be OO
> language neutral.
>
> Several classes are specified as being abstract; so therefore there
> should be no instances of them, correct?
>
> However in the classes that are subclasses what is the correct way in
> Python to implement them?

That very much depends on the classes, and how much the abstract classes
do.  With the very simple examples you give which have no methods even,
I'd be strongly tempted not to implement the classes at all.  But let's
assume that's not a good idea (and there are plenty of reasons for it
not to be a good idea, to be fair).

Caution: I am not in the slightest bit familiar with the zope.interface
module, which does make your IA and IB classes look exceptionally
pointless.  Again, it's fairly safe to presume that I'm wrong there :-)

> I am using the zope.interface module as well.
>
> For example:
>
> class IA(Interface):
>    m = Int()
>    p = TextLine()
>
> class IB(Interface):
>
>    x = Bool()
>    s = Text()
>
>
>
> class A(object):
> """ This is an abstract class with attributes m is an int and p is a
> string"""
>
>    implements(IA)
>    pass
>
> class B(A):
>   implements(IB)
>
>   def __init__(self,m,p,x,s):
>     m=m
>     p=p
>     x=x
>     s=s

Presumably you mean
     self.m = m
     self.p = p
and so on?

This doesn't seem to be a consistent approach.  Class B enforces
initialisation of all its attributes, including the inherited ones,
but class A doesn't.

> or should it be like:
>
> class A(object):
> """ This is an abstract class with attributes m is an int and p is a
> string"""
>
>    implements(IA)
>
>    def __init__(self,m,p):
>      m=m
>      p=p
>
>
> class B(A):
>   implements(IB)
>
>   def __init__(self,m,p,x,s):
>     A.__init__(m,p)
>     x=x
>     s=s

Modulo the "self." as before, this is more consistent.

> or maybe even:
>
> class B(A):
>   implements(IB)
>
>   def __init__(self,m,p,x,s):
>     super(A.__init__(m,p))
>     x=x
>     s=s

I have a bit of an allergy to super() because it works in slightly
unexpected ways.  Here in particular it doesn't gain you anything
and may cost you instead.

-- 
Rhodri James *-* Wildebeeste Herder to the Masses



More information about the Python-list mailing list