a single class supporting multiple facets/interfaces

David Garamond davegaramond at icqmail.com
Mon Jan 20 07:46:36 EST 2003


i want to have a class that can support multiple sets of methods, based 
on what the client requests. for example, see the following code:

<<EOF
class C:
     def foo(self):
         print "foo"
     def bar1(self):
         print "bar version 1"
     def bar2(self, arg):
         print "bar version 2, arg =", arg
     def facet(self, whichFacet=1):
         if whichFacet == 1:
             return C_facet1(self)
         elif whichFacet == 2:
             return C_facet2(self)
         return

class C_facet1:
     def __init__(self, c):
         self.foo = c.foo
         self.bar = c.bar1

class C_facet2:
     def __init__(self, c):
         self.foo = c.foo
         self.bar = c.bar2

c1 = C().facet(1) # client1 picks interface1
c1.foo()          # prints "foo"
c1.bar()          # prints "bar version 1"

c2 = C().facet(2) # client2 picks interface2
c2.foo()          # prints "foo"
c2.bar(123)       # prints "bar version 2, arg = 123"
EOF

if a client wants interface 1, then she will get foo and bar (which is 
actually bar1). if he picks interface 2, then she will get foo and bar 
(which is actually bar2). for all she cares, she just wants to know/deal 
with a single [versatile] class, C. and from that single class, she can 
pick several sets of features/interfaces she needs/wants.

the above code does what i want to accomplish, but i think it's very 
ugly. can anyone make it more elegant?

-- 
dave






More information about the Python-list mailing list