Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Zope interfaces can provide a useful way to decouple two pieces of code that shouldn't depend on each other.</p> <p>Say we have a component that knows how to print a greeting in module a.py:</p> <pre><code>&gt;&gt;&gt; class Greeter(object): ... def greet(self): ... print 'Hello' </code></pre> <p>And some code that needs to print a greeting in module b.py:</p> <pre><code>&gt;&gt;&gt; Greeter().greet() 'Hello' </code></pre> <p>This arrangement makes it hard to swap out the code that handles the greeting without touching b.py (which might be distributed in a separate package). Instead, we could introduce a third module c.py which defines an IGreeter interface:</p> <pre><code>&gt;&gt;&gt; from zope.interface import Interface &gt;&gt;&gt; class IGreeter(Interface): ... def greet(): ... """ Gives a greeting. """ </code></pre> <p>Now we can use this to decouple a.py and b.py. Instead of instantiating a Greeter class, b.py will now ask for a utility providing the IGreeter interface. And a.py will declare that the Greeter class implements that interface:</p> <pre><code>(a.py) &gt;&gt;&gt; from zope.interface import implementer &gt;&gt;&gt; from zope.component import provideUtility &gt;&gt;&gt; from c import IGreeter &gt;&gt;&gt; @implementer(IGreeter) ... class Greeter(object): ... def greet(self): ... print 'Hello' &gt;&gt;&gt; provideUtility(Greeter(), IGreeter) (b.py) &gt;&gt;&gt; from zope.component import getUtility &gt;&gt;&gt; from c import IGreeter &gt;&gt;&gt; greeter = getUtility(IGreeter) &gt;&gt;&gt; greeter.greet() 'Hello' </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload