Reusing object methods?

Jp Calderone exarkun at divmod.com
Fri Apr 29 14:10:54 EDT 2005


On Fri, 29 Apr 2005 19:45:54 +0200, Ivan Voras <ivoras at _-_fer.hr> wrote:
>
>Can this be done: (this example doesn't work)
>
>----
>class A:
>
>     def a_lengthy_method(self, params):
>          # do some work depending only on data in self and params
>
>class B:
>
>     def __init__(self):
>         self.a_lengthy_method = A.a_lengthy_method
>         # I know that data in "self" of class B object is compatible
>         # with that of class A object
>----
>
>I want to 'reuse' the same method from class A in class B, and without 
>introducing a common ancestor for both of them - is this possible in an 
>elegant, straightforward way?

  This is what sub-classing is for.  If it makes you feel better, call it "mixing in" instead.  You can share this method between two classes without inheritance (by defining a free function and then ...), but using a common base class really is just the right way to do it.

  Jp



More information about the Python-list mailing list