method override inside a module

Steve Holden steve at holdenweb.com
Fri May 25 08:17:28 EDT 2007


Fabrizio Pollastri wrote:
> Hello,
> I am trying to override a method of a class defined into an imported 
> module, but keeping intact the namespace of the imported module.
> 
> 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()
> 	...
> 
> Thanks in advance for any help.
> 
The names of things don't count for that much in Python (though classes, 
methods and functions *are* associated with their names).

Have you tried something like

module_X.A.method_1 = method_1

module_x.py:

class A:
   def __init__(self):
     print "Creating an A"
   def method_1(self, arg):
     print "Calling original method_1 with argument", arg


test20.py:

import module_X

a1 = module_X.A()

def method_1(self, arg):
   print "Calling substituted method_1 with", arg

module_X.A.method_1 = method_1

a2 = module_X.A()

a1.method_1('banana')
a2.method_1('orange')

Running it:

sholden at bigboy ~/Projects/Python
$ python test20.py
Creating an A
Creating an A
Calling substituted method_1 with banana
Calling substituted method_1 with orange

As you can see, even if you created objects before you tinkered witht he 
class definition they still get the new method (because it's looked up 
and found in the class).

This kind of activity is called "monkey patching", and is sometimes a 
useful technique to alter a module for one specific application. Try not 
to take it too far, though.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
------------------ Asciimercial ---------------------
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.com        squidoo.com/pythonology
tagged items:         del.icio.us/steve.holden/python
All these services currently offer free registration!
-------------- Thank You for Reading ----------------




More information about the Python-list mailing list