Commits

Henning Schröder committed 820aa68

simple parameter dispatching for multiplle constructors

Comments (0)

Files changed (1)

 from console import debug
 from collections import namedtuple
 
+    
+_dispatch_map = {}
+
+def dispatch(*types):
+    def wrapper(func):
+        def inner(*args, **kwargs):
+            arg_types = tuple([type(a) for a in args])
+            key = (getattr(func, "im_self", ""), func.__name__, arg_types)
+            real_func =_dispatch_map.get(key)
+            return real_func(*args, **kwargs)
+        key = (getattr(func, "im_self", ""), func.__name__, types)
+        _dispatch_map[key] = func
+        return inner
+    return wrapper
+
+
+
 
 class TSize(object):
     __slots__ = ("width", "height")
 
-    
+
+    @dispatch(int, int)
     def __init__(self, width, height):
         self.width = width
         self.height = height
 
-        
+
     def __cmp__(self, other):
         return cmp((self.width, self.height), (other.width, other.height))
 
 
 class TPoint(object):
     __slots__ = ("x", "y")
-    
+
+
+    @dispatch(int,int)
     def __init__(self, x, y):
         self.x = x
         self.y = y
 class TRect(object):
     __slots__ = ("_topLeft", "_size")
 
-
+    
+    
+    @dispatch(TPoint, TSize)
     def __init__(self, point, size):
         self._topLeft = point
         self._size = size
 
 
+    @dispatch(int,int,int,int)
+    def __init__(self, x1, y1, width, height):
+        self._topLeft = TPoint(x1,y1)
+        self._size = TSize(width,height)
+    
+        
     @property
     def size(self):
         return self._size
     
 
 
+
+
+
+
+    
+if __name__ == "__main__":
+    @dispatch(int)
+    def test(v):
+        print v, "is int"
+        
+    @dispatch(float)
+    def test(v):
+        print v, "is float"
+        
+
+    test(1)
+    test(1.0)