Stylistic question about inheritance



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:

class Expr(object):
pass

class UnaryExpr(Expr):
# ...

class BinaryExpr(Expr):
# ...

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?


.



Relevant Pages

  • Re: Changing return of type(obj)
    ... the base class on an instance by instance basis depending on the need? ... now I can imagine having a class factory that will spawn for me the class ...
    (comp.lang.python)
  • Re: set a property of inherited class from base class
    ... Where the property name is "panel1", ... For example, you can have that property virtual/abstract on the base class, ... the reflection overhead. ... I imagine i have to use reflection, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: set a property of inherited class from base class
    ... > I am trying to get set a property of a control on the inherited class from ... I imagine i have to use reflection, ... of an instance of a inherited class from an instance of the base class then ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Some thoughts about OO programming
    ... type code which is exactly what polymorphism is supposed to help fix. ... in general that's called the fragile base class problem. ... interface IAnimal2: public IAnimal ... reasons to avoid it, many of which you address in your post. ...
    (comp.programming)
  • Re: Stylistic question about inheritance
    ... > might want it so that type queries such as isinstance ... Are there other reasons to create a base class when I ...
    (comp.lang.python)