Function Overloading and Python

castironpi at gmail.com castironpi at gmail.com
Mon Feb 25 10:27:07 EST 2008


On Feb 25, 1:33 am, Allen Peloquin <tandonm... at gmail.com> wrote:
> I have a personal project that has an elegant solution that requires
> both true multiple inheritance of classes (which pretty much limits my
> language choices to C++ and Python) and type-based function
> overloading.
>
> Now, while this makes it sound like I have to resign myself to C++,
> which I am not a fan of writing, I have resisted thus far. Who wants
> to manage their own memory? No, I have fallen in love with Python, and
> so come asking for help.
>
> I have a very large multiple inheritance tree that will be frequently
> extended as my project goes on. Let us call these "type A" classes.
>
> I also have a moderately sized single inheritance tree whose task is
> to match sets of "type A" parameters in a function. Let us call these
> "type B" classes. "Type Bs" have one function, which is extended with
> each new child, and overloaded to match varying combinations of "Type
> As." The reason for this is code-reuse and eventual matching with
> common "type A" parents.
>
> Now, what are my options in Python to dispatch unique code based on
> the permutations of "type A" classes without code repetition?
> Such as, where in C++...
>
> 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.
>
> B1.fun(A(x), A(y), A(z)) == B.fun(A(x), A(y), A(z))
> but
> B1.fun(A1(x), A(y), A(z) != B.fun(A1(x), A(y), A(z))
>
> Is there a data-structure solution or third party module that would
> mimic this behavior?
>
> PEP 3124 got my hopes up, but I was let down when it was deferred.
>
> Thank you for your time.

Does the decorator solution work in this case?

class B:
   @multimethod( A, A, A )
   def fun( x, y, z )
   @multimethod( A1, A, A )
   def fun( x, y, z )

class B1:
   @multimethod( A1, A, A )
   def fun( x, y, z )

b= B1()
b.fun( A(), A(), A() ) -> B.fun#.1
b.fun( A1(), A(), A() ) -> B1.fun#.2



More information about the Python-list mailing list