Stylistic question about inheritance

"Martin v. Löwis" martin at v.loewis.de
Thu Mar 31 15:18:17 EST 2005


Andrew Koenig wrote:
> Of course, there are reasons to have a base class anyway.  For example, I 
> might want it so that type queries such as isinstance(foo, Expr) work.  My 
> question is: Are there other reasons to create a base class when I don't 
> really need it right now?

You would normally try to avoid type queries, and rely on virtual
methods instead, if possible. It seems likely for the application
that code can be shared across different subclasses, for example,
you might be able to define

def Expr:
   def __str__(self):
     return '%s(%s)' % (self.__class__.__name__,
                        ", ".join(map(str, self.operands()))

requiring you only to implement .operands() in the subclasses.

If you can anticipate such common code, it is easier to add
a base class right away. If you cannot think of a specific
use case, there is little point in having a common base class.

Regards,
Martin



More information about the Python-list mailing list