a single class supporting multiple facets/interfaces

Peter Abel p-abel at t-online.de
Wed Jan 22 07:37:46 EST 2003


David Garamond <davegaramond at icqmail.com> wrote in message news:<mailman.1043066796.28044.python-list at python.org>...
> 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
I'm not capable to understand, what you want to do, what
inheritance can't do better, clearer and better to maintain:
> class C:
>      def foo(self):
>          print "foo"
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):

Here you have to decide for the first time,
which Interface you want!

>          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_facet1(C):
  def bar(self,arg='')
    print ""bar version 1"
> 
> class C_facet2:
>      def __init__(self, c):
>          self.foo = c.foo
>          self.bar = c.bar2

class C_facet2(C):
  def bar(self,arg='')
    print "bar version 2, arg =", arg

> 
Here you have to decide for the second time,
which Interface you want!

> c1 = C().facet(1) # client1 picks interface1

c1=C_facet1() # client1 picks interface1

> c1.foo()          # prints "foo"

c1.foo()          # prints "foo"


> c1.bar()          # prints "bar version 1"

c1.bar()          # prints "bar version 1"

> 
> c2 = C().facet(2) # client2 picks interface2

c2=C_facet2() # client2 picks interface2

> c2.foo()          # prints "foo"
> c2.bar(123)       # prints "bar version 2, arg = 123"

... and so on ...

> 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?

This is exactly that, what inheritance does and is for.

Or am I wrong?

Peter




More information about the Python-list mailing list