-
Notifications
You must be signed in to change notification settings - Fork 0
/
overload.py
40 lines (37 loc) · 1.04 KB
/
overload.py
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
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)
function = self.typemap.get(types)
if function is None:
raise TypeError("no match")
return function(*args)
def register(self, types, function):
self.typemap[types] = function
def overload(*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
@overload(int, int)
def area(length, breadth):
calc = length * breadth
print (calc)
@overload(int)
def area(size):
calc = size * size
print (calc)
@overload(int,int,int)
def area(adj,opp,hyp):
calc = adj * opp*hyp
print (calc)
area(3) # returns 9
area(4,5) # returns 20
area(4,5,6) # returns 20