How to replace a method in an instance.
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Wed Aug 22 01:30:50 EDT 2007
Steven W. Orr a écrit :
> In the program below, I want this instance to end up calling repmeth
> whenever inst.m1 is called. As it is now, I get this error:
>
> Hello from init
> inst = <__main__.CC instance at 0x402105ec>
> Traceback (most recent call last):
> File "./foo9.py", line 17, in ?
> inst.m1()
> TypeError: repmeth() takes exactly 1 argument (0 given)
>
>
> #! /usr/bin/python
> def repmeth( self ):
> print "repmeth"
>
> class CC:
> def __init__( self ):
> self.m1 = repmeth
> print 'Hello from init'
>
> def m1 ( self ):
> print "m1"
>
> inst = CC()
> inst.m1()
>
> TIA
# using old-style classes:
import new
def repmeth( self ):
print "repmeth"
class CC:
def __init__( self ):
self.m1 = new.instancemethod(repmeth, self, type(self))
print 'Hello from init'
def m1 ( self ):
print "m1"
inst = CC()
inst.m1()
# using newstyle classes:
def repmeth( self ):
print "repmeth"
class CC(object):
def __init__( self ):
self.m1 = repmeth.__get__(self, type(self))
print 'Hello from init'
def m1 ( self ):
print "m1"
inst = CC()
inst.m1()
HTH
More information about the Python-list
mailing list