Short recipe for adaptation with Five

>>> from zope.interface import Interface, Attribute, implements

Let's say we have an object type "Person". This person can introduce himself with the name.

class IPerson(Interface):
name = Attribute('Name of the person')
    def say_name():
        """The name of the person"""

class Person(object):
    implements(IPerson)

    def __init__(self, name):
       self.name = name

    def say_name():
        return 'My name is ' + self.name

Next, we have another object type, let's say "Worker", with an interface of IWorker.

class IWorker(Interface):
job = Attribute('Name of the job')
def set_job():
"""sets the job"""

def say_job():
"""the job"""

Now we want to adapt the Person so that a person is also a Worker.

class PersonJob(object):
implements(IWorker)

def __init__(self, context):
self.context = context

def set_job(self, job):
self.job = job

def say_job(self):
return "My name is %s and I work at %s" % (self.context.name, self.job)

Now let's register the factory that implements the Worker for a Person.

#### >>> registry.register(IPerson, [IWorker,], '', PersonJob)

<configure xmlns="http://namespaces.zope.org/zope">
<adapter
for=".IPerson"
provides=".IWorker"
factory=".PersonJob" />
</configure>

Now let's see how this works

>>> Tom = Person('Tom Sawyer')
>>> print Tom.say_name()
'My name is Tom Sawyer'
>>> tomjob = IWorker(Tom)
>>> tomjob.set_job('DisneyLand')
>>> tomjob.say_job()
'My name is Tom Sawyer and I work at DisneyLand'

Further reference:

Comments