-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultiMethod.py
More file actions
53 lines (46 loc) · 1.17 KB
/
multiMethod.py
File metadata and controls
53 lines (46 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#From: Five-minute Multimethods in Python
# by Guido van van Rossum
# http://www.artima.com/weblogs/viewpost.jsp?thread=101605
#Modified to support inheritance
registry = {}
class MultiMethod(object):
def __init__(self, name):
self.name = name
self.typemap = {}
def __call__(self, *args):
types = tuple(arg.__class__ for arg in args) # a generator expression!
function = self.typemap.get(types)
if function is None:
raise TypeError("no match")
return function(*args)
def register(self, types, function):
if types in self.typemap:
raise TypeError("duplicate registration")
self.typemap[types] = function
def multimethod(*types):
def register(function):
name = function.__name__
mm = registry.get(name)
if mm is None:
mm = registry[name] = MultiMethod(name)
mm.register(types, function)
return mm
return register
#class A(object):
# pass
#
#class B(A):
# pass
#
#@multimethod(int,int)
#def foo(a,b):
# print 'int'
#
#@multimethod(A,A)
#def foo(a,b):
# print 'works'
#
#
#a = A()
#b = B()
#foo(a,b)