a single class supporting multiple facets/interfaces

David Garamond davegaramond at icqmail.com
Wed Jan 22 02:51:02 EST 2003


Jp Calderone wrote:
> from twisted.python import components
> 
> class C(components.Componentized):
>     # C class definition omitted for brevity/clarity
>     pass
> 
> class IGoodStuff(components.Interface):
>     def foo(self):
>         """Display some fooey goodness"""
> 
>     def bar(self):
>         """Display some quality bar"""
> 
> 
> class CAdapter(components.Adapter):
>     def foo(self):
>         self.original.foo()
> 
> class VersionOneAdapter(CAdapter):
>     __implements__ = (IGoodStuff,)
> 
>     def bar(self):
>         self.original.bar1()
> 
> class VersionTwoAdapter(CAdapter):
>     __implements__ = (IGoodStuff,)
> 
>     def bar(self):
>         self.original.bar2()
> 
> # Set the adapter to be used for this interface globally
> components.registerAdapter(VersionOneAdapter, C, IGoodStuff)
> c1 = C()
> c1.getComponent(IGoodStuff).bar()
> 
> # Override the global setting for this instance only
> c1.setComponent(IGoodStuff, VersionTwoAdapter(c1))
> c1.getComponent(IGoodStuff).bar()

thanks. yes, actually "interface" and "component" do pretty much what i 
envision. the components module from Twisted looks like it might be 
something cool.

to correct myself and the previous example, the original requirement is 
for a single class (component) C to implement two facets (interfaces). 
let's call the two interfaces IGoodStuff1 and IGoodStuff2.

class IGoodStuff1(components.Interface):
     def foo(self): pass
     def bar1(self): pass
class IGoodStuff2(components.Interface):
     def foo(self): pass
     def bar2(self, arg): pass

and since i don't think i want more than one Adapters for a single 
component-interface link -- in other words: a component never implements 
a single interface twice, differently -- can i do away without adapters 
in this case? i.e.: i want to move the "adapter stuff" (like the 
'__implements__' declaration) directly in C. something like this:

class C(components.Componentized):
     __implements__ = (IGoodStuff1, IGoodStuff2)
     def foo1(self):
         # will implement IGoodStuff1's foo
     def foo2(self):
         # will implement IGoodStuff2's foo
     def bar1(self):
         # will implement IGoodStuff1's bar1
     def bar2(self):
         # will implement IGoodStuff1's bar2

the problem is of course the 'foo' name conflict.

-- 
dave






More information about the Python-list mailing list