dumb q: repeated inheritance in python?

John Roth newsgroups at jhrothjr.com
Thu Sep 11 17:24:04 EDT 2003


"Corey Coughlin" <corey.coughlin at attbi.com> wrote in message
news:a8623416.0309111319.14334945 at posting.google.com...
> Hi, here's a silly question.  I'm wrote some code a while back that
> looks like this:
>
> import types
>
> class Named(object):
>     def __init__(self,nm=''):
>         self.iname = ''
>         self.setnm(nm)
>     def setnm (self,nm):
>         if isinstance(nm, types.StringType):
>             self.iname = nm
>         else:
>             raise TypeError, "Name passed to Named isn't a string."
>     def getnm (self):
>         return self.iname
>     name = property(getnm,setnm)
>
> Pretty basic, a name attribute with simple type checking, it works
> fine and the code using it is fine.  Well, it was, until I came up
> with an object that needed two names, with the same basic type
> checking.  Now the simplistic way to do that would be copy this class
> to another class, say Named2, rename the property name2 and be done
> with it.  On the other hand, having code that's basically an exact
> duplicate of other code except for some name changes seems a tad
> inelegant.  What I'd really like to do is inherit this same object
> twice, but the second time rename the objects so that I get 'name2'
> instead of 'name'.  (And somehow rename the functions, and so on.)
>
> But I can't figure out how to do it.  Is there some way to do this?  I
> suspect there might be some way to do it with metaclasses, but I
> haven't really wrapped my head around that stuff yet.  Maybe something
> with the new 'super' keyword?  Beats me.  Anyway, any help would be
> great, thanks!!!

Why do the two names have to be in the same object instance? I'd
think the simplest approach would be to bind two instances of your
Named class to two different identifiers.

Otherwise, if you actually need some kind of a collection class, I'd
purpose build one: NamedCollection, or some such.

John Roth






More information about the Python-list mailing list