Skip to content

Instantly share code, notes, and snippets.

@simongarisch
Created October 16, 2019 00:47
Show Gist options
  • Save simongarisch/0dcb47daaee6ae9a1e2eb6db8a0dffa9 to your computer and use it in GitHub Desktop.
Save simongarisch/0dcb47daaee6ae9a1e2eb6db8a0dffa9 to your computer and use it in GitHub Desktop.
Python structural patterns - adaptor
# adaptor - integrate classes with otherwise incompatible interfaces.
class Man:
def talk(self):
print("Blah de blah")
class Cat:
def make_noise(self):
print("Meow de meow!")
class Adapter:
def __init__(self, obj, **adapted_methods):
self._obj = obj
self.__dict__.update(adapted_methods)
def __getattr__(self, attr):
''' All non-adapted calls should pass to the object '''
return getattr(self._obj, attr)
man = Man()
cat = Cat()
adapted_cat = Adapter(cat, talk=cat.make_noise)
man.talk() # Blah de blah
adapted_cat.talk() # Meow de meow
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment