Stylistic question about inheritance
ark at acm.org
Thu Mar 31 21:33:31 CEST 2005
Suppose I want to define a class hierarchy that represents expressions, for
use in a compiler or something similar.
We might imagine various kinds of expressions, classified by their top-level
operator (if any). So, an expression might be a primary (which, in turn,
might be a variable or a constant), a unary expression (i.e. the result of
applying a unary operator to an expression), a binary expression, and so on.
If I were solving such a problem in C++, I would define a base class for all
expressions, then derive the various kinds of expression classes from that
base class. However, I would not anticipate ever creating objects of the
base class, so I would make it abstract.
In Python, I can imagine doing the same thing:
and so on. However, although I don't have a choice in C++ about having a
base class--you can't use dynamic binding without it--in Python I do have
that choice. That is, I don't need to have the base class at all unless I
want to have some operations that are common to all derived classes.
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?
More information about the Python-list