469,270 Members | 1,762 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,270 developers. It's quick & easy.

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?
Jul 18 '05 #1
17 1585

Andrew Koenig wrote:
[snip]
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?


Well, Python seems to get along fine without the ability to do
isinstance(foo,file_like_object); probably better off in the end for
it. So I'd say you should generally not do it. Inheritence is for
when different classes need to share functionality.
--
CARL BANKS

Jul 18 '05 #2
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
Jul 18 '05 #3
"Carl Banks" <in**********@aerojockey.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com...
Well, Python seems to get along fine without the ability to do
isinstance(foo,file_like_object); probably better off in the end for
it. So I'd say you should generally not do it. Inheritence is for
when different classes need to share functionality.


That's really the question: Is it for when they need to share
functionality, or when they are conceptually related in ways that might lead
to shared functionality later?
Jul 18 '05 #4
If you try this sort of inheritance, I'd recommend writing down the
formal grammar before you start writing classes. Don't try to define
the grammar through the inheritance hierarchy; it's too easy to
accidentally build a hierarchy that can't be translated into a
single-pass-parsable grammar...

I usually skip the inheritance and make everything an instance of the
same class, e.g.

class ASTNode(object): ...

class Stmt(ASTNode): ...
class Expr(ASTNode): ...
class UnaryExpr(ASTNode): ...
class BinaryExpr(ASTNode): ...

or you could dynamically generate classes with inheritance based on a
grammar definition

Jul 18 '05 #5
""Martin v. Lwis"" <ma****@v.loewis.de> wrote in message
news:42**************@v.loewis.de...
You would normally try to avoid type queries, and rely on virtual
methods instead, if possible.
Of course.
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.
Indeed.
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.


So, for example, you don't think it's worth including the base class as a
way of indicating future intent?
Jul 18 '05 #6
"Lonnie Princehouse" <fi**************@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
If you try this sort of inheritance, I'd recommend writing down the
formal grammar before you start writing classes. Don't try to define
the grammar through the inheritance hierarchy; it's too easy to
accidentally build a hierarchy that can't be translated into a
single-pass-parsable grammar...
Understood. I was using expression trees as a contrived example, and really
want to know about the Python community's stylistic preferences for defing
such hierarchies that don't absolutely need a root.
I usually skip the inheritance and make everything an instance of the
same class, e.g.

class ASTNode(object): ...

class Stmt(ASTNode): ...
class Expr(ASTNode): ...
class UnaryExpr(ASTNode): ...
class BinaryExpr(ASTNode): ...


Eh? There's still inheritance here: Everything is derived from ASTNode. I
understand that there is a separate design issue whether to make the
hierarchy deep or shallow, but it's still a hierarchy.

Jul 18 '05 #7
Andrew Koenig wrote:
"Lonnie Princehouse" <fi**************@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...

If you try this sort of inheritance, I'd recommend writing down the
formal grammar before you start writing classes. Don't try to define
the grammar through the inheritance hierarchy; it's too easy to
accidentally build a hierarchy that can't be translated into a
single-pass-parsable grammar...

Understood. I was using expression trees as a contrived example, and really
want to know about the Python community's stylistic preferences for defing
such hierarchies that don't absolutely need a root.


I have used empty or near-empty base classes to be some sort of
class 'tag' for the derived classes.
Much like Java's Serializable interface; it adds nothing on
a functional level but you can check if a class has a 'tag'
by checking if it is an instance of the base class.
I don't know if this is good style in Python but I tend
to use it sometimes (probably because I do Java at work ;-)

--Irmen
Jul 18 '05 #8
In article
<P_*********************@bgtnsc05-news.ops.worldnet.att.net>,
"Andrew Koenig" <ar*@acm.org> wrote:
"Carl Banks" <in**********@aerojockey.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com...
Well, Python seems to get along fine without the ability to do
isinstance(foo,file_like_object); probably better off in the end for
it. So I'd say you should generally not do it. Inheritence is for
when different classes need to share functionality.


That's really the question: Is it for when they need to share
functionality, or when they are conceptually related in ways that might lead
to shared functionality later?


No -- inheritance is for implementation, not to express conceptual
relationship.

Donn Cave, do**@u.washington.edu
Jul 18 '05 #9
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?


Coming from C++ myself, I still prefer to use inheritance even if Python
doesn't force me to do it. It's simply a matter of mapping the conceptual
model to the actual design/implementation, if ever possible.

Regards,
Stefan
Jul 18 '05 #10
Andrew Koenig wrote:
So, for example, you don't think it's worth including the base class as a
way of indicating future intent?


No. In this respect, I believe in XP: refactor when the need comes up,
but not before.

Regards,
Martin
Jul 18 '05 #11
On Thu, 31 Mar 2005 20:24:08 GMT, "Andrew Koenig" <ar*@acm.org> wrote:
""Martin v. Lwis"" <ma****@v.loewis.de> wrote in message
news:42**************@v.loewis.de...
You would normally try to avoid type queries, and rely on virtual
methods instead, if possible.


Of course.
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.


Indeed.
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.


So, for example, you don't think it's worth including the base class as a
way of indicating future intent?

If the intent is pretty sure of implementation, I guess it will save some
editing to include it at the start (unless you intended to define old-style classes
and factor the base class inheritance revisions into some global metaclass hack later
(not even really sure that's reliably possible, but pretty sure it would not be the
best style ;-) BTW 2.5 may let you mod classes by prefixing a decorator instead of
editing the first line. Not sure about the style/semantics tradeoffs there.

Regards,
Bengt Richter
Jul 18 '05 #12
Andrew Koenig wrote:
"Carl Banks" <in**********@aerojockey.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com...
Well, Python seems to get along fine without the ability to do
isinstance(foo,file_like_object); probably better off in the end for
it. So I'd say you should generally not do it. Inheritence is for
when different classes need to share functionality.


That's really the question: Is it for when they need to share
functionality, or when they are conceptually related in ways that might lead
to shared functionality later?


I've typically only done the former. But I've definitely extracted
common ancestors later when I did find that two different classes should
share functionality.

STeVe
Jul 18 '05 #13
Well, that's true, but I meant to convey that no grammatical entity is
the base class of another entity, so it's a flat inheritance tree in
that respect. ASTNode would not be something that the parser would
know anything about.

I guess that's sort of moot if your expression trees are just a
contrived example; in that case, I'd say that how deep you want your
inheritance hierarchy to be depends entirely on how your program wants
to use it.

Jul 18 '05 #14
Koenig:
want to know about the Python community's stylistic
preferences for defing
such hierarchies that don't absolutely need a root.


I don't know if there is an official style guide or a Guido's
prononcement on the issue. Personally
I found such hierarchies attractive in the past, but
recently I realized that they look better on the paper
than in practice. A non-needed class just adds cognitive
burden to the maintainer. Also, I don't like to use
isinstance if I can avoid it. Finally, It is always easy to
refactor later and to add a base class
if there is a real need for it.
Paraphrasing Occam, I would say "don't multiply base classes without
necessity" ;)
Michele Simionato

Jul 18 '05 #15
Hi All--

Michele Simionato wrote:

recently I realized that they look better on the paper
than in practice. A non-needed class just adds cognitive
burden to the maintainer.
Agreed. Too many classes make me think I'm back trying to figure out
what the )(*#@$ those guys were thinking making 200 twelve-line ASP
classes. Ya think there's a hard-wired limit past which your brain
melts?
Paraphrasing Occam, I would say "don't multiply base classes without
necessity" ;)


+1 QOTW

Metta,
Ivan
----------------------------------------------
Ivan Van Laningham
God N Locomotive Works
http://www.andi-holmes.com/
http://www.foretec.com/python/worksh...oceedings.html
Army Signal Corps: Cu Chi, Class of '70
Author: Teach Yourself Python in 24 Hours
Jul 18 '05 #16
Andrew Koenig wrote:
""Martin v. Lwis"" <ma****@v.loewis.de> wrote in message
news:42**************@v.loewis.de...

You would normally try to avoid type queries, and rely on virtual
methods instead, if possible.

Of course.

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.

Indeed.

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.

So, for example, you don't think it's worth including the base class as a
way of indicating future intent?

The obvious XP response to the question is "You aren't going to need
it". If you already have the intent then basically you appear to be
saying "I *am* going to need it".

Since you say that almost as an integral feature of the specification
I'm not sure I understand why you asked the question in the first place
- unless it's really an anthropological inquiry.

regards
Steve
--
Steve Holden +1 703 861 4237 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/

Jul 18 '05 #17
"Andrew Koenig" <ar*@acm.org> writes:
"Lonnie Princehouse" <fi**************@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
If you try this sort of inheritance, I'd recommend writing down the
formal grammar before you start writing classes. Don't try to define
the grammar through the inheritance hierarchy; it's too easy to
accidentally build a hierarchy that can't be translated into a
single-pass-parsable grammar...


Understood. I was using expression trees as a contrived example, and really
want to know about the Python community's stylistic preferences for defing
such hierarchies that don't absolutely need a root.


Oddly enough, I've just been pondering the same question (albeit for
Perl, but the same reasoning applies). The only cases I've found
useful thus far are:

- implementation inheritance (in the case of default methods in a
callback interface class):

class CallbackInterface:

def handleEvent(self, event):
"""Handle an event"""
pass

def handleSignal(self, signal):
"""Handle a signal"""
pass

This also helps to document what's expected of callback classes,
even though they don't _have_ to inherit CallbackInterface
(enforcing this through isinstance() in the calling class would be
rude).

- hierarchies of exception classes (allowing one to catch general
classes of exceptions, since except implicitly uses isinstance(),
rather than a specific class). Of course, Python already has a
hierarchy of exceptions. I had to implement my own for Perl.

From a brief skim of http://www.python.org/moin/PythonThreeDotOh it
looks like interfaces _may_ be added to Python 3.0, but they sound
more like (IIRC) ML's signatures and C++'s Standard Library
requirements i.e. a requirement that the class implements certain
functions, rather than a requirement to inherit from a particular base
class.

Guy.
Jul 18 '05 #18

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Stephan Diehl | last post: by
13 posts views Thread by Chris Smith | last post: by
4 posts views Thread by Russell Silva | last post: by
2 posts views Thread by Tony Johansson | last post: by
1 post views Thread by Tony Johansson | last post: by
60 posts views Thread by Mark Healey | last post: by
14 posts views Thread by JoeC | last post: by
3 posts views Thread by Jess | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.