extending methods ?

David C. Fox davidcfox at post.harvard.edu
Wed Oct 1 10:31:03 EDT 2003


Arnd Baecker wrote:
> Hi,
> 
> the summary of my question is:
> is there a way to append commands to a method inherited from
> another class?
> 
> More verbose: Assume the following situation that I have
> a class class_A with several methods.
> In each of these methods quite a few computations take place
> and several variables are defined.
> Now I would like to extend this class to a class_B.
> However, instead of overriding a method completely,
> I would like to extend the method by basically adding
> further commands at the end.
> 
> Eg., the code could look like:
> 
> class class_A:
>     def method1(self,x):
>         y=5*x+1                 # create a variable
> 
> 
> class class_B(class_A):
>     appendto method1(self,x):
>         print y                 # use variable defined in class_A
> 
> 
> I.e. Effictively class_B should "look" like:
> 
> class class_B(class_A):
>     def method1(self,x):
>         y=5*x+1                 # create a variable
>         print y                 # use the variable
> 

If you really want to do this, you are probably better off doing it 
explicitly.  For example


class A:
     def store_locals(self, local_variables, keep_locals):
         if keep_locals is None:
             return
         keep_locals.update(local_variables)

     def m(self, x, keep_locals = None):
         """If you want to keep the local variables of this method,
         specify a dictionary for keep_locals
         """
         y = 5*x+1
         self.store_locals(locals(), keep_locals)


class C(A):
     def m(self, x, keep_locals = None):
         if keep_locals is None:
             keep_locals = {}
         v = A.m(self, x, keep_locals = keep_locals)
         print 'y was ', keep_locals['y']
         return v


> P.S.: Sorry if I messed up things on the OO side
>       (I am a real new-comer to this ...;-).

Perhaps if you tell us more about why you want to do this, we could come 
up with a better OO solution.

David





More information about the Python-list mailing list