How to replace a method in an instance.

  • Thread starter Bruno Desthuilliers
  • Start date
B

Bruno Desthuilliers

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
 
B

Bruno Desthuilliers

(e-mail address removed) a écrit :
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
 
S

Steven W. Orr

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
 
K

kyosohma

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
 
S

Steven W. Orr

On Friday, Aug 24th 2007 at 09:12 -0700, quoth (e-mail address removed):

=>> 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
 
W

Wildemar Wildenburger

Steven said:
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
 
J

James Stroud

Steven said:
On Friday, Aug 24th 2007 at 09:12 -0700, quoth (e-mail address removed):

=>> 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:

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



James
 
S

Steven W. Orr

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

=>On Friday, Aug 24th 2007 at 09:12 -0700, quoth (e-mail address removed):
=>
=>=>> 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
 
J

James Stroud

Steven said:
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:


py> def f1(self):
.... print 'f1'
....
py> def f2(self):
.... print 'f2'
....
py> 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
....
py> Aclass = classfactory()
py> Aclass().doit()
doit
py>
py> Aclass2 = classfactory({'doit':f1, 'doit2':f2})
py> Aclass().doit2()
doit2
py> Aclass2().doit2()
f2


James
 
J

J. Cliff Dyer

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

=>On Friday, Aug 24th 2007 at 09:12 -0700, quoth (e-mail address removed):
=>
=>=>> 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
 
K

kyosohma

(e-mail address removed) a écrit :





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...


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
 
J

James Stroud

I'm not going to help with these class / instance / whatever any more
and leave it to all you professionals.

Wrong again. Stick your neck out, look like an ass, and then
learn--alot. That's what I do.

Your misinformation will be corrected, even if you are chastised in the
process.

James



--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
 
B

Bruno Desthuilliers

(e-mail address removed) a écrit :
(snip)



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

I'd think that at least some authors of some Python books would explain
all this much better than I did. But FWIW, all these rules are clearly
documented in the Fine Manual.
(snip)
I'm not going to help with these class / instance / whatever any more
and leave it to all you professionals.

How do you think I learned ? One of the big things with usenet is that
you get a chance to be corrected when you're wrong, and I personnally
owe a lot of thanks to all the people that corrected me so far and still
correct me.
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,

Indeed, Steve's problem was that the function he attached to his
instance was *not* wrapped into a method object.
 
A

Alex Martelli

I'd think that at least some authors of some Python books would explain
all this much better than I did. But FWIW, all these rules are clearly
documented in the Fine Manual.

Speaking as one such author, I think I do a reasonable job of this in
"Python in a Nutshell" (2nd ed): on p. 82 and 85 I have brief mentions
that "class attributes bound to functions are also known as methods of
the class" (p.82) and again that "functions (called methods in this
context) are important attributes for most class objects" (p.85); on
p.91-94, after explaining descriptors, instances, and the basics of
attribute reference, I can finally cover the subject thoroughly in
"Bound and Unbound Methods". I realize that a beginner might be
confused into believing that "class attributes bound to functions" means
"function in a class", if they stop reading before p.91;-), but I don't
literally make that wrong assertion...;-)


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top