a single class supporting multiple facets/interfaces

Terry Reedy tjreedy at udel.edu
Mon Jan 20 13:08:15 EST 2003


[cc'ed]
"David Garamond" <davegaramond at icqmail.com> wrote in message
news:mailman.1043066796.28044.python-list at python.org...
> the above code does what i want to accomplish, but i think it's very
> ugly. can anyone make it more elegant?

I am slightly surprised at how often people post questions like the
above.
To me, any code which is straightforward (comprehensible on one
reading), easy to change, and which accomplishes the goal intended,
has a certain kind of beauty.
Code does not have to be ugly to be improvable.

That said, I believe you could also do what you want by deriving your
master class from object (to make it 'new-style') and the facet
classes from the master class.  Then provide a factory function which
returns an instance of the desired subclass.
Something like

def giveme(choice):
  return {1:sub1, 2:sub2, 3:sub3}[choice]()

To change the interface of existing instances, provide another
function that changes __class__ (or let clients know that they can).
The following experiment indicates that this should work.

>>> class c(object):
...   def f(s): print s
...
>>> class c1(c): pass
...
>>> cc=c()
>>> cc.f()
<__main__.c object at 0x00792170>
>>> cc.__class__ = c1
>>> cc.f()
<__main__.c1 object at 0x00792170>

Perhaps you can do this with classic classes, don't know.

Terry J. Reedy






More information about the Python-list mailing list