Created
February 16, 2013 19:42
-
-
Save spidaman/4968401 to your computer and use it in GitHub Desktop.
python polymorphism w/class methods
This file contains 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
class WtfException(Exception): | |
pass | |
class AdaptiveResponse(object): | |
def __init__(self, params, message): | |
self.params = params | |
self.message = message | |
def __repr__(self): | |
return "params: {0} message: {1}".format(self.params, self.message) | |
class BaseAdaptation(object): | |
@staticmethod | |
def get(params): | |
# assure that the class methods we expect to have | |
# derivations implement do so | |
raise WtfException("WTF? Method not implemented") | |
class HerpAdaptation(BaseAdaptation): | |
@staticmethod | |
def get(params): | |
# too legit to quit | |
return AdaptiveResponse(params,"herptastic") | |
class DerpAdaptation(BaseAdaptation): | |
@staticmethod | |
def get(params): | |
# legit | |
return AdaptiveResponse(params,"derptastic") | |
class FailedAdaptation(BaseAdaptation): | |
# not legit, doesn't implement get(...) | |
pass | |
""" | |
AdaptiveService Usage: | |
>>> from service import AdaptiveService | |
>>> AdaptiveService.get("derp", {"foo": "bar"}) | |
params: {'foo': 'bar'} message: derptastic | |
>>> AdaptiveService.get("herp", {"foo": "bar"}) | |
params: {'foo': 'bar'} message: herptastic | |
>>> AdaptiveService.get("fail", {"foo": "bar"}) | |
Traceback (most recent call last): | |
File "<stdin>", line 1, in <module> | |
File "service.py", line 15, in get | |
return config[adaptation_type].get(params) | |
File "adaptations.py", line 17, in get | |
raise WtfException("WTF? Method not implemented") | |
adaptations.WtfException: WTF? Method not implemented | |
>>> AdaptiveService.get("berp", {"foo": "bar"}) | |
Traceback (most recent call last): | |
File "<stdin>", line 1, in <module> | |
File "service.py", line 17, in get | |
raise WtfException("Dunno WTF {0} is".format(adaptation_type)) | |
adaptations.WtfException: Dunno WTF berp is | |
""" | |
config = { | |
'derp': DerpAdaptation, | |
'herp': HerpAdaptation, | |
'fail': FailedAdaptation | |
} | |
class AdaptiveService(object): | |
@staticmethod | |
def get(adaptation_type, params={}): | |
if adaptation_type in config: | |
return config[adaptation_type].get(params) | |
else: | |
raise WtfException("Dunno WTF {0} is".format(adaptation_type)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment