a single class supporting multiple facets/interfaces

Mike Meyer mwm at mired.org
Tue Jan 21 12:28:26 EST 2003


David Garamond <davegaramond at icqmail.com> writes:

> 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

You can do this slightly cleaner if you're willing to use inheritance.

class C:
    # as before, except no arguments passed to C_facet? in facet.

class C_facet1(C):
    bar = C.bar1

class C_facet2(C):
    bar = C.bar2
  

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.




More information about the Python-list mailing list