Skip to content

Instantly share code, notes, and snippets.

@xarg
Created November 24, 2011 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xarg/1391374 to your computer and use it in GitHub Desktop.
Save xarg/1391374 to your computer and use it in GitHub Desktop.
Apples and Oranges with an zope component adapter
from zope.component import getGlobalSiteManager, adapts
from zope.interface import Interface, implements
class IApple(Interface):
"""I'm an apple"""
class Apple:
implements(IApple) # we need this so we can adapt this class
worm = "~~~"
class Orange:
def slices(self):
return [1, 2, 3]
class ISlicedApple(Interface):
"""interface of the adapted apple"""
def slices():
""" Return slices """
class SlicedApple:
""""""
implements(ISlicedApple)#same as for utility
adapts(IApple)#the interface which we augment
def __init__(self, apple):
self.apple = apple#setting up the adaptee
def slices(self):
self.apple.worm = None #remove the worm
return [1, 2, 3, 4]
def get_slices(basket):
"""For each item in the basket get it's slices"""
slices = []
for item in basket:
slices.append(item.slices())
return slices
if __name__ == '__main__':
gsm = getGlobalSiteManager()
#Same as the utility
gsm.registerAdapter(SlicedApple)
#Now that we can get our adapted apple.
#Notice that we query using the interface and not the implementation SlicedApple
adapted_apple = gsm.getAdapter(Apple(), ISlicedApple)
basket = []
basket.append(Orange())
basket.append(adapted_apple)
print get_slices(basket)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment