473,469 Members | 1,685 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

How to replace a method in an instance.

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
Aug 24 '07 #1
10 1884
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()

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

Aug 24 '07 #2
On Friday, Aug 24th 2007 at 09:12 -0700, quoth ky******@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
Aug 24 '07 #3
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.

/W
Aug 24 '07 #4
Steven W. Orr wrote:
On Friday, Aug 24th 2007 at 09:12 -0700, quoth ky******@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
Aug 24 '07 #5
On Friday, Aug 24th 2007 at 12:26 -0400, quoth Steven W. Orr:

=>On Friday, Aug 24th 2007 at 09:12 -0700, quoth ky******@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
Aug 24 '07 #6
Steven W. Orr wrote:
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
Aug 24 '07 #7
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
Aug 24 '07 #8
ky******@gmail.com a écrit :
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()

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...
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
Aug 24 '07 #9
Steven W. Orr wrote:
On Friday, Aug 24th 2007 at 12:26 -0400, quoth Steven W. Orr:

=>On Friday, Aug 24th 2007 at 09:12 -0700, quoth ky******@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
Aug 24 '07 #10
On Aug 22, 12:48 am, Bruno Desthuilliers
<bdesth.quelquech...@free.quelquepart.frwrote:
kyoso...@gmail.com a écrit :
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()
>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...
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.

>
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

Aug 24 '07 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Terry Olson | last post by:
I want to search a textbox and replace any instances of the dollar sign character. But when I do that it thinks it won't work because it think's I'm looking to replace something at the end of the...
3
by: Chua Wen Ching | last post by:
Hi there, I just read Chris Sells's article at http://www.codeproject.com/csharp/delegate_bedtime.asp?df=100&forumid=2983&select=922269#xx922269xx I wonder i can do this: 1) I want to...
10
by: pamelafluente | last post by:
I need to replace all the occurences of a string within another string (or stringbuilder): Function ReplaceInsensitive(ByVal InputString As String, _ ByVal SubstringReplaced As String, _ ByVal...
23
by: digitalorganics | last post by:
How can an object replace itself using its own method? See the following code: class Mixin: def mixin(object, *classes): NewClass = type('Mixin', (object.__class__,) + classes, {}) newobj =...
5
by: Brian Blais | last post by:
Hello, I want to replace a method in a class during run-time with another function. I tried the obvious, but it didn't work: class This(object): def update(self,val): print val def...
4
by: Morgan Cheng | last post by:
In my case, I have to remove any line containing "0.000000" from input string. In below case, it takes about 100 ms for 2k size input string. Regex.Replace(inputString, ".*0\\.000000.*\n", ""); I...
3
by: Pascal | last post by:
bonjour hello I would like to trim a string of all its white spaces so i used myString.trim() but it doesn't work as supposed : unsecable space are remaining in the middle of my string... i...
10
by: Lonifasiko | last post by:
Hi, Just want to replace character at index 1 of a string with another character. Just want to replace character at that position. I thought Replace method would be overloaded with an index...
10
by: hofer | last post by:
Hi, 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...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.