Skip to content

Instantly share code, notes, and snippets.

@timhughes
Created March 14, 2020 13:06
Show Gist options
  • Save timhughes/74115d2f49a25c9ce827bf639d6c2504 to your computer and use it in GitHub Desktop.
Save timhughes/74115d2f49a25c9ce827bf639d6c2504 to your computer and use it in GitHub Desktop.
python ABCMeta example
from abc import ABCMeta, abstractmethod
class SomeClass:
def __init__(self):
pass
def another_request(self):
print('test')
class ITarget(metaclass = ABCMeta):
"""
Define the domain-specific interface that Client uses.
https://docs.python.org/3/library/abc.html#abc.abstractmethod
The abstractmethod() only affects subclasses derived using regular
inheritance; “virtual subclasses” registered with the ABC’s register()
method are not affected.
"""
@abstractmethod
def request(self):
pass
@abstractmethod
def whatever(self):
pass
class Adaptee:
"""
Define an existing interface that needs adapting.
"""
def specific_request(self):
print('This is the output')
pass
class Adapter(ITarget, SomeClass):
"""
Adapt the interface of Adaptee to the ITarget interface by implementing the target interface
"""
def __init__(self, adaptee):
self._adaptee = adaptee
def request(self):
self._adaptee.specific_request()
def whatever(self):
pass
def main():
adaptee = Adaptee()
adapter = Adapter(adaptee)
adapter.request()
adapter.another_request()
adapter.whatever()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment