query regarding OOP functionality in python
Josiah Carlson
jcarlson at uci.edu
Mon Apr 5 18:50:29 EDT 2004
> If you absolutely must have these features, stick to C++ or Java.
Or do something crazy like this...
Error = '''\
Received signature of: %s
Expected one of: %s'''
class polymorpher(object):
def __init__(self):
self._dict = {}
def add_funct(self, funct, *argtypes):
self._dict[argtypes] = funct
def __call__(self, *args, **kwargs):
t = tuple(map(type, args))
try:
f = self._dict[(t,)]
except KeyError:
raise TypeError(Error%(t, self._dict.keys()))
return f(*args, **kwargs)
>>> funct = polymorpher()
>>> funct.add_funct(lambda *args:str(args), (int, int))
>>> funct.add_funct(lambda *args:str(args), (float, int))
>>> funct(1,2)
(<type 'int'>, <type 'int'>)
'(1, 2)'
>>> funct(1.5, 6)
(<type 'float'>, <type 'int'>)
'(1.5, 6)'
>>> funct(1, 1.5)
(<type 'int'>, <type 'float'>)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 12, in __call__
TypeError: Received signature of: [<type 'int'>, <type 'float'>]
Expected one of: [((<type 'float'>, <type 'int'>),), ((<type 'int'>,
<type 'int'>),)]
>>>
Ahh, polymorphism.
- Josiah
More information about the Python-list
mailing list