Can methods and functions be overloaded?
Carel Fellinger
cfelling at iae.nl
Fri Feb 16 10:24:36 EST 2001
More information about the Python-list mailing list
Fri Feb 16 10:24:36 EST 2001
- Previous message (by thread): Sping (was PIDDLE) not producing PDF file
- Next message (by thread): PRoblem with UDP sockets
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Steve Holden <sholden at holdenweb.com> wrote: ... > Does this help, or did you alredy know about it? I'm afraid Python doesn't > allow the same kind of method overloading by signature that, say, Java and > C++ do. Right, but you can build your own:) class Overload: def __init__(self): self.fun = {} def __call__(self, *args): try: fun = self.fun[self.signature(*args)] except KeyError: raise TypeError, "invalid overloading signature" return fun(*args) def signature(self, *args): '''smart up if you need to play with class hierarchies''' return tuple([type(x) for x in args]) def overload(self, fun, *args): self.fun[self.signature(*args)] = fun class Overloaded: def __init__(self): f = self.f = Overload() f.overload(self.f_None) f.overload(self.f_num, 1) f.overload(self.f_num, 1.0) f.overload(self.f_string, "1") f.overload(self.f_more, 'spam', 1) def f_None(self): return None def f_num(self, n): return n * 3 def f_string(self, s): return 'string is %s' % s def f_more(self, s, n): return s * n o = Overloaded() print o.f() print o.f(10) print o.f(5.4) print o.f("spam", 9) print o.f(9, "spam") this yields: None 30 16.2 spamspamspamspamspamspamspamspamspam Traceback (most recent call last): File "t.py", line 48, in ? print o.f(9, "spam") File "t.py", line 9, in __call__ raise TypeError, "invalid overloading signature" TypeError: invalid overloading signature -- groetjes, carel
- Previous message (by thread): Sping (was PIDDLE) not producing PDF file
- Next message (by thread): PRoblem with UDP sockets
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list