Last active
August 29, 2015 14:08
-
-
Save darkfeline/a611fa1ea494a98424ec to your computer and use it in GitHub Desktop.
Python multimethods (Clojure style)
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 MultiMethod: | |
def __init__(self, func): | |
self.func = func | |
self.methods = {} | |
def __call__(self, *args, **kwargs): | |
return self.methods[self.func(*args, **kwargs)](*args, **kwargs) | |
def method(self, case): | |
def method_adder(func): | |
self.methods[case] = func | |
return self | |
return method_adder | |
to_string = MultiMethod(lambda x: x.__class__) | |
@to_string.method(str) | |
def to_string(self): | |
return "string" | |
@to_string.method(int) | |
def to_string(self): | |
return "integer" | |
print(to_string("hi")) | |
print(to_string(1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment