Created
October 16, 2019 00:47
-
-
Save simongarisch/0dcb47daaee6ae9a1e2eb6db8a0dffa9 to your computer and use it in GitHub Desktop.
Python structural patterns - adaptor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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