Reusing object methods?
Joal Heagney
jhe13586 at bigpond.net.au
Sun May 1 11:31:09 EDT 2005
Axel Straschil wrote:
> Hello!
>
> Why not:
>
>
>>class A:
>> def a_lengthy_method(self, params):
>> # do some work depending only on data in self and params
>>
>>class B(A): pass
>
>
> ?
>
> Lg,
> AXEL.
As a rough guess, I think the original poster was wondering how to
include *one* specific method from class A into B, without including all
the methods of A. Jp Calderone's suggestion of defining a special Mixin
class seems to be the cleanest implementation.
E.g.
class MyMixin:
""" Defines only a single method. It may be a debug call, or
a replacement for the classes' string representation. Etc. """
def a_lengthy_method(self,params):
# do some work
class A(MyMixin):
def other_lengthy_procedures(self, params):
pass
class B(MyMixin):
pass
The advantage of this is that you can define a normal inheritance tree
for a variety of classes, and then specifically override a single (or
group) of methods by placing the MyMixin class at the front of the
inheritance call. (The book "Programming Python" uses this a LOT in the
Tkinter section.)
E.g.
class C:
def well_now_what_do_we_do(self):
# stuff
def a_lengthy_method(self,params):
# This does the wrong stuff.
class D(MyMixin, C):
def __init__(self):
# blahblahblah
Now class D has the "correct" a_lengthy_method, inherited from MyMixin,
as well as all the other methods from class C, and the methods defined
in it's own class statement.
Joal
More information about the Python-list
mailing list