method override inside a module

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri May 25 07:33:09 EDT 2007


En Fri, 25 May 2007 06:12:14 -0300, Fabrizio Pollastri  
<pollastri at iriti.cnr.it> escribió:

> I am trying to override a method of a class defined into an imported
> module, but keeping intact the namespace of the imported module.

The last part I don't get completely...

> For example, let suppose
>
> 	import module_X
>
> and in module_X is defined something like
>
> 	class A:
>
>            ...
>
>            def method_1():
>              ...
>
> 	  ...
>
> I wish to override method_1 with a new function and to call the
> overrided method inside my application with the same name of the
> original method like
>
> 	...
> 	module_X.method_1()
> 	...

I think you meant to say:
   someAinstance = module_X.A(...)
   someAinstance.method_1(...)

If you import module_X in a SINGLE module, in THAT module you could use:

import module_X
class A(module_X.A):
   def method_1()...

and create all your instances using A(). (This is the traditional  
approach, you modify the original class by inheritance).
Notice that the important thing is where you *create* your instances:  
other modules that import module_X but do not create A instances are  
unaffected; they will use your modified class anyway.

If you import module_X in several places, and you create A instances in  
several places too, you may "monkey-patch" the A class. Somewhere at the  
*start* of your application, you can write:

def method_1(self, ...):
    ... new version of method_1

import module_X
module_X.A.method_1 = method_1

You are effectively replacing the method_1 with another one.

-- 
Gabriel Genellina




More information about the Python-list mailing list