Connecting Tech Pros Worldwide Forums | Help | Site Map

How to replace a method in an instance.

Steven W. Orr
Guest
 
Posts: n/a
#1: Aug 24 '07
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

--
Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net

kyosohma@gmail.com
Guest
 
Posts: n/a
#2: Aug 24 '07

re: How to replace a method in an instance.


On Aug 24, 11:02 am, "Steven W. Orr" <ste...@syslang.netwrote:
Quote:
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
>
--
Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
Remove "self" from repmeth as it's not required in a function, only in
functions that are defined within a class. Of course, a function in a
class is also know as a method.

Mike

Steven W. Orr
Guest
 
Posts: n/a
#3: Aug 24 '07

re: How to replace a method in an instance.


On Friday, Aug 24th 2007 at 09:12 -0700, quoth kyosohma@gmail.com:

=>On Aug 24, 11:02 am, "Steven W. Orr" <ste...@syslang.netwrote:
=>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()

=>Remove "self" from repmeth as it's not required in a function, only in
=>functions that are defined within a class. Of course, a function in a
=>class is also know as a method.

Sorry. I need repmeth to have self passed to it automatically if it's
called. I didn't mean to obfuscate the problem by not making a reference
to self in repmeth.

Am I being clear?

--
Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
Wildemar Wildenburger
Guest
 
Posts: n/a
#4: Aug 24 '07

re: How to replace a method in an instance.


Steven W. Orr wrote:
Quote:
Sorry. I need repmeth to have self passed to it automatically if it's
called. I didn't mean to obfuscate the problem by not making a reference
to self in repmeth.
>
Am I being clear?
>
>
Sort of. Maybe you fare better if you state what you want to achieve,
instead of how you think you should do it. Chances are you don't need to
replace a method in __init__, but there's another, less tricky way.

/W
James Stroud
Guest
 
Posts: n/a
#5: Aug 24 '07

re: How to replace a method in an instance.


Steven W. Orr wrote:
Quote:
On Friday, Aug 24th 2007 at 09:12 -0700, quoth kyosohma@gmail.com:
>
=>On Aug 24, 11:02 am, "Steven W. Orr" <ste...@syslang.netwrote:
=>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()
>
=>Remove "self" from repmeth as it's not required in a function, only in
=>functions that are defined within a class. Of course, a function in a
=>class is also know as a method.
>
Sorry. I need repmeth to have self passed to it automatically if it's
called. I didn't mean to obfuscate the problem by not making a reference
to self in repmeth.
At least you are consistent in that you obfuscate every question.

Here's what you seem to want:



import types

def repmeth(self):
print "repmeth"

# inherit from object!
class CC(object):
def __init__(self):
self.m1 = types.MethodType(repmeth, self)
print 'Hello from init'
def m1(self):
print 'm1'

inst = CC()
inst.m1()



Output:

pyimport types
py>
pydef repmeth(self):
.... print "repmeth"
....
py# inherit from object!
pyclass CC(object):
.... def __init__(self):
.... self.m1 = types.MethodType(repmeth, self)
.... print 'Hello from init'
.... def m1(self):
.... print 'm1'
....
pyinst = CC()
Hello from init
pyinst.m1()
repmeth



James
Steven W. Orr
Guest
 
Posts: n/a
#6: Aug 24 '07

re: How to replace a method in an instance.


On Friday, Aug 24th 2007 at 12:26 -0400, quoth Steven W. Orr:

=>On Friday, Aug 24th 2007 at 09:12 -0700, quoth kyosohma@gmail.com:
=>
=>=>On Aug 24, 11:02 am, "Steven W. Orr" <ste...@syslang.netwrote:
=>=>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()
=>
=>=>Remove "self" from repmeth as it's not required in a function, only in
=>=>functions that are defined within a class. Of course, a function in a
=>=>class is also know as a method.
=>
=>Sorry. I need repmeth to have self passed to it automatically if it's
=>called. I didn't mean to obfuscate the problem by not making a reference
=>to self in repmeth.
=>
=>Am I being clear?

On Friday, Aug 24th 2007 at 18:44 +0200, quoth Wildemar Wildenburger:

=>Steven W. Orr wrote:
=>Sorry. I need repmeth to have self passed to it automatically if it's
=>called. I didn't mean to obfuscate the problem by not making a
reference
=>to self in repmeth.
=>>
=>Am I being clear?
=>>
=>>
=>Sort of. Maybe you fare better if you state what you want to achieve,
=>instead of how you think you should do it. Chances are you don't need to
=>replace a method in __init__, but there's another, less tricky way.

Ok. I have a collection of classes that are produced by a factory. They
all inherit from a baseclass. One (maybe more) of the classes inherits a
method that he shouldn't. All I want is to be able to change that
particular class so that he will have the special method that he needs
instead of the default one that he inherits. I was thinking that instead
of making a special class for CC to inherit from which would give him his
special replacement method(s), I could simply assign them in a manner
which would more easily lend itself to later being table driven.

If I had a choice, I'd rather not do it in init. Instead, I'd rather be
able to say something like
CC.m1 = repmeth
but since in the real world, CC inherits from his baseclass, the above
assignment causes the baseclass to be altered. :-(

Please tell me if I need to provide more.

--
Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
James Stroud
Guest
 
Posts: n/a
#7: Aug 24 '07

re: How to replace a method in an instance.


Steven W. Orr wrote:
Quote:
Ok. I have a collection of classes that are produced by a factory. They
all inherit from a baseclass. One (maybe more) of the classes inherits a
method that he shouldn't. All I want is to be able to change that
particular class so that he will have the special method that he needs
instead of the default one that he inherits. I was thinking that instead
of making a special class for CC to inherit from which would give him his
special replacement method(s), I could simply assign them in a manner
which would more easily lend itself to later being table driven.
>
If I had a choice, I'd rather not do it in init. Instead, I'd rather be
able to say something like
CC.m1 = repmeth
but since in the real world, CC inherits from his baseclass, the above
assignment causes the baseclass to be altered. :-(
>
Please tell me if I need to provide more.

def f1(self):
print 'f1'

def f2(self):
print 'f2'

def classfactory(replacements=None):
class _C(object):
def doit(self):
print 'doit'
def doit2(self):
print 'doit2'
if replacements is not None:
for fname, f in replacements.items():
setattr(_C, fname, f)
return _C

Aclass = classfactory()
Aclass().doit()

Aclass2 = classfactory({'doit':f1, 'doit2':f2})
Aclass().doit2()
Aclass2().doit2()



Here's the output:


pydef f1(self):
.... print 'f1'
....
pydef f2(self):
.... print 'f2'
....
pydef classfactory(replacements=None):
.... class _C(object):
.... def doit(self):
.... print 'doit'
.... def doit2(self):
.... print 'doit2'
.... if replacements is not None:
.... for fname, f in replacements.items():
.... setattr(_C, fname, f)
.... return _C
....
pyAclass = classfactory()
pyAclass().doit()
doit
py>
pyAclass2 = classfactory({'doit':f1, 'doit2':f2})
pyAclass().doit2()
doit2
pyAclass2().doit2()
f2


James
Bruno Desthuilliers
Guest
 
Posts: n/a
#8: Aug 24 '07

re: How to replace a method in an instance.


Steven W. Orr a écrit :
Quote:
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
Bruno Desthuilliers
Guest
 
Posts: n/a
#9: Aug 24 '07

re: How to replace a method in an instance.


kyosohma@gmail.com a écrit :
Quote:
On Aug 24, 11:02 am, "Steven W. Orr" <ste...@syslang.netwrote:
>
Quote:
>>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
>>
>
Remove "self" from repmeth as it's not required in a function, only in
functions that are defined within a class.
Obviously wrong. 'self' (or whatever-you-name-it) as first arg is
mandatory for functions used as instance methods. The fact that a
function is defined outside a class doesn't mean it cannot be used as a
method...
Quote:
Of course, a function in a
class is also know as a method.
Less obvious but still wrong !-)

A function object, whereever (and however) it's defined, is a function
object, not a method objet. Now what happens is that functions defined
inside a class are wrapped in method (by default, instancemethod) objects.

To be more accurate - and talking only about how it works for new-style
classes - function objects implements the descriptor protocol, so when a
function is a class attribute (which is what happens when the function
is defined in the class statement's body), and is looked up on an
instance, it returns an instancemethod object that has the instance and
the function as attributes. This instancemethod object is itself
callable, and when called returns the result of calling the function
with the instance as first argument. classmethods and staticmethods are
variants fo this scheme, calling the function with either the class as
first arg (for classmethods) or just as-is (for staticmethods).

Now when you set a function as an *instance* (not class) attribute, the
descriptor protocol isn't invoked (it only works on class attributes),
so if you want to use the function as a method, you have to do the
wrapping by yourself (cf my other answer to the OP).

HTH
J. Cliff Dyer
Guest
 
Posts: n/a
#10: Aug 24 '07

re: How to replace a method in an instance.


Steven W. Orr wrote:
Quote:
On Friday, Aug 24th 2007 at 12:26 -0400, quoth Steven W. Orr:
>
=>On Friday, Aug 24th 2007 at 09:12 -0700, quoth kyosohma@gmail.com:
=>
=>=>On Aug 24, 11:02 am, "Steven W. Orr" <ste...@syslang.netwrote:
=>=>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()
=>
=>=>Remove "self" from repmeth as it's not required in a function, only in
=>=>functions that are defined within a class. Of course, a function in a
=>=>class is also know as a method.
=>
=>Sorry. I need repmeth to have self passed to it automatically if it's
=>called. I didn't mean to obfuscate the problem by not making a reference
=>to self in repmeth.
=>
=>Am I being clear?
>
On Friday, Aug 24th 2007 at 18:44 +0200, quoth Wildemar Wildenburger:
>
=>Steven W. Orr wrote:
=>Sorry. I need repmeth to have self passed to it automatically if it's
=>called. I didn't mean to obfuscate the problem by not making a
reference
=>to self in repmeth.
=>>
=>Am I being clear?
=>>
=>>
=>Sort of. Maybe you fare better if you state what you want to achieve,
=>instead of how you think you should do it. Chances are you don't need to
=>replace a method in __init__, but there's another, less tricky way.
>
Ok. I have a collection of classes that are produced by a factory. They
all inherit from a baseclass. One (maybe more) of the classes inherits a
method that he shouldn't. All I want is to be able to change that
particular class so that he will have the special method that he needs
instead of the default one that he inherits. I was thinking that instead
of making a special class for CC to inherit from which would give him his
special replacement method(s), I could simply assign them in a manner
which would more easily lend itself to later being table driven.
>
If I had a choice, I'd rather not do it in init. Instead, I'd rather be
able to say something like
CC.m1 = repmeth
but since in the real world, CC inherits from his baseclass, the above
assignment causes the baseclass to be altered. :-(
>
Please tell me if I need to provide more.
>
>
Is there a reason you don't just create a subclass for the one that
needs to call repmeth?

class CC(object):
def m1(self):
print "m1"
def m2(self):
print "m2"

class SpecialCC(CC):
def m1(self):
print "something else!"

if __name__ == '__main__':
a = CC()
b = SpecialCC()
for instance in a, b:
instance.m1()
instance.m2()

--Output--
m1
m2
something else!
m2


Is that what you're looking for, mas o menos?

Cheers,
Cliff
kyosohma@gmail.com
Guest
 
Posts: n/a
#11: Aug 24 '07

re: How to replace a method in an instance.


On Aug 22, 12:48 am, Bruno Desthuilliers
<bdesth.quelquech...@free.quelquepart.frwrote:
Quote:
kyoso...@gmail.com a écrit :
>
>
>
Quote:
On Aug 24, 11:02 am, "Steven W. Orr" <ste...@syslang.netwrote:
>
Quote:
Quote:
>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:
>
Quote:
Quote:
>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)
>
Quote:
Quote:
>#! /usr/bin/python
>def repmeth( self ):
print "repmeth"
>
Quote:
Quote:
>class CC:
def __init__( self ):
self.m1 = repmeth
print 'Hello from init'
>
Quote:
Quote:
def m1 ( self ):
print "m1"
>
Quote:
Quote:
>inst = CC()
>inst.m1()
>
Quote:
Quote:
>TIA
>
Quote:
Remove "self" from repmeth as it's not required in a function, only in
functions that are defined within a class.
>
Obviously wrong. 'self' (or whatever-you-name-it) as first arg is
mandatory for functions used as instance methods. The fact that a
function is defined outside a class doesn't mean it cannot be used as a
method...
>
Quote:
Of course, a function in a
class is also know as a method.
>
Less obvious but still wrong !-)

I wish the authors of the Python books would get a clue then.

Quote:
>
A function object, whereever (and however) it's defined, is a function
object, not a method objet. Now what happens is that functions defined
inside a class are wrapped in method (by default, instancemethod) objects.
>
To be more accurate - and talking only about how it works for new-style
classes - function objects implements the descriptor protocol, so when a
function is a class attribute (which is what happens when the function
is defined in the class statement's body), and is looked up on an
instance, it returns an instancemethod object that has the instance and
the function as attributes. This instancemethod object is itself
callable, and when called returns the result of calling the function
with the instance as first argument. classmethods and staticmethods are
variants fo this scheme, calling the function with either the class as
first arg (for classmethods) or just as-is (for staticmethods).
>
Now when you set a function as an *instance* (not class) attribute, the
descriptor protocol isn't invoked (it only works on class attributes),
so if you want to use the function as a method, you have to do the
wrapping by yourself (cf my other answer to the OP).
>
HTH
I'm not going to help with these class / instance / whatever any more
and leave it to all you professionals.

Yes, it you can use self in an outside method, but the way the OP
asked the question and the nature of the traceback pointed to it just
being a normal function, not a method since the OP wasn't passing an
argument to the bugger.

Oh well. Live and learn to unlearn what you learned.

Mike

Closed Thread