replace mothod for only one object but not for a class

hofer blabla at dungeon.de
Wed Oct 15 11:57:28 CEST 2008


Hi

> > hofer a écrit :
> >> I have multiple objects all belonging to the same class
> >>  (which I didn't implement and whose code I don't want to modify)
>
> >> Now I'd like to change one method for one object only (after it has
> >> been created) without adding any overhead
> >> to the call of the other object's methods.

Thanks for all of your answers:

Here an example with three of the suggested solutions:
(I didn't succeed in implementing Jason's solution with my
example)

########################################################
import threading
# some objects
a = threading.Event()
b = threading.Event()
c = threading.Event()
d = threading.Event()

def run_dly(o): # a test function
    print o,"start",
    o.wait(1)
    print "stop"

# unmodified test
run_dly(a)
run_dly(b)
run_dly(c)
run_dly(d)

# The new Method
def verbose_wait(self,dly):
    print "VERBOSE",
    threading._Event.wait(self,dly)

### Implemented with partial
from functools import partial
b.wait = partial(verbose_wait,b)

###   with __get__ for new classes
c.wait = verbose_wait.__get__(c,type(c))

## with new for old classes
import new
d.wait = new.instancemethod(verbose_wait,d,type(d))

run_dly(a)
run_dly(b)
run_dly(c)
run_dly(d)
############# end
thanks again

Hofer




More information about the Python-list mailing list