Function Overloading and Python

Stefan Behnel stefan_ml at behnel.de
Mon Feb 25 03:04:28 EST 2008


Allen Peloquin wrote:
> On Feb 24, 11:44 pm, Stefan Behnel <stefan... at behnel.de> wrote:
>> Allen Peloquin wrote:
>>> class B
>>> {
>>>     fun(A x, A y, A z)...
>>>     fun(A1 x, A y, A z)...
>>> }
>>> class B1
>>> {
>>>     fun(A1 x, A y, A z)...
>>> }
>>> Such that any previous behavior is inherited, but behaves
>>> polymorphically because of the single function name.
>> Try something like this:
>>
>> class B(object):
>>     def fun(x,y,z):
>>         if isinstance(x, A1):
>>             return self._fun(x,y,z)
>>         # ...
>>
>>     def _fun(x,y,z):
>>         # ...
>>
>> class B1(B):
>>     def _fun(x,y,z):
>>         # ...
>>
>> Stefan
> 
> The problem is that I want to reuse the code of the parent classes
> through inheritance, otherwise this would work fine.

Ok, I didn't see you were going to add new subtypes, that makes it more tricky
to dispatch in the superclass.

An alternative would be a more generic dispatcher pattern then:

   class B(object):
       _func_implementations = {}
       _dispatch = _func_implementations.get

       def func(self, x,y,z):
           self._dispatch(type(x), self._func)(self,x,y,z)

       def _func(self, x,y,z):
           # ...

    class B1(B):
       def _func(self, x,y,z):
           # ...

    B._func_implementations[B1] = B1._func

Or, you could dispatch based on type /names/:

   class B(object):
       def func(self, x,y,z):
           func = getattr(self, "_%s_func" % type(x).__name__, self._func)
           func(x,y,z)

       def _A_func(self, x,y,z):
           # ...

    class B1(B):
       def _A1_func(self, x,y,z):
           # ...

Stefan



More information about the Python-list mailing list