Instances behaviour

Peter Otten __peter__ at web.de
Fri Dec 2 04:09:12 EST 2005


Mr.Rech wrote:

> Suppose I have a bunch of classes that represent slightly (but
> conceptually) different object. The instances of each class must behave
> in very similar manner, so that I've created a common class ancestor
> (let say A) that define a lot of special method (such as __getattr__,
> __setattr__, __len__ and so on), and then I've created all my "real"
> classes inheriting from it:
> 
>>>>class A(object):
> ....     # here define all special and some common methods
> 
>>>> class B(A):
> ....    # this is the first "real" class
> 
>>>> class C(A):
> ....    # and this is the second
> 
> and so on. The problem I'm worried about is that an unaware user may
> create an instance of "A" supposing that it has any real use, while it
> is only a sort of prototype. However, I can't see (from my limited
> point of view) any other way to rearrange things and still get a
> similar behaviour.
> 
> Implementing those special methods directly in class B and then inherit
> from it, doesn't seem the right way, since I'd prefer that instances of
> B weren't in any relation with the instances of C (i.e. I'd prefer not
> to subclass C from B)
> 
> Perhaps some OOP techniques (that I miss at the moment) could be of any
> help. Any suggestion?

How about

class A(object):
    """Provides common functionality for A-like classes, e. g. B and C.
    
    Do not instantiate.
    """ 

This is definitely a low-tech approach, but I suppose you don't clutter your
functions with spurious argument type checks, either.
An exception like the one shown by Inyeol Lee is typically raised once
during the development process while my approach bites (only) the
illiterate programmer with a message like

>>> a.foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'A' object has no attribute 'foo'

which normally can be tracked down almost as quickly -- and which serves him
well anyway :-)

Peter




More information about the Python-list mailing list