473,624 Members | 2,258 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

replace a method in class: how?

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 another_update( obj,val):
print "another",v al

t=This()
t.update(5)
t.update=anothe r_update
t.update(5) # this one doesn't work, gives
# TypeError: another_update( ) takes exactly 2 arguments (1 given)
clearly it isn't seeing it as a method, just an attribute which happens to be a
function. Is there a preferred way to do this?
thanks,

Brian Blais
--
-----------------

bb****@bryant.e du
http://web.bryant.edu/~bblais
Jun 26 '06 #1
5 6848
On 27/06/2006 9:14 AM, Brian Blais wrote:
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 another_update( obj,val):
print "another",v al

t=This()
t.update(5)
t.update=anothe r_update
t.update(5) # this one doesn't work, gives
# TypeError: another_update( ) takes exactly 2 arguments (1 given)
clearly it isn't seeing it as a method, just an attribute which happens
to be a function. Is there a preferred way to do this?


You have a strange definition of "obvious". You say you want to replace
a method in a *class*, not in an instance of that class ... so just do that:

|>> class This(object):
.... def update(self,val ):
.... print val
....
|>> def another_update( obj,val):
.... print "another",v al
....
|>> This.update = another_update
|>> t = This()
|>> t.update(42)
another 42

Cheers,
John
Jun 26 '06 #2
Brian Blais a écrit :
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 another_update( obj,val):
print "another",v al

t=This()
t.update(5)
t.update=anothe r_update
This is not "replacing a method in a class", but replacing it in an
instance.
t.update(5) # this one doesn't work, gives
# TypeError: another_update( ) takes exactly 2 arguments (1 given)
clearly it isn't seeing it as a method, just an attribute which happens
to be a function. Is there a preferred way to do this?


import types
t.update = types.MethodTyp e(another_updat e)
Jun 26 '06 #3
I don't know a ton about this, but it seems to work if you use:
This.update = another_update
(instead of t.update = another_update)
after saying This.update = another_update, if you enter This.update, it
says <unbound method This.another_up date>, (it's unbound)
but if you call
t.update(5)
it will print:
another 5

Jun 26 '06 #4
Le mardi 27 juin 2006 05:05, Bruno Desthuilliers a écrit*:
import types
t.update = types.MethodTyp e(another_updat e)


This works with :

t.update = types.MethodTyp e(another_updat e, t)

Oh, this *really* misleading what the intent of the programmer is, and

In [29]: t.update
Out[29]: <bound method ?.<lambda> of <__main__.a instance at 0xa774d96c>>

all let think it's a method defined in t's class.
I prefer early binding with default parameters :

In [30]: def another_update( self, param) :pass
....:

In [31]: t.update = lambda x, self=t : another_update( self, x)

In [32]: t.update = lambda x, self=t, func=another_up date : func(self, x)

In [33]: t.update
Out[33]: <function <lambda> at 0xa7744aac>

So we have a function and know it (probably) belongs to the instance.

--
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
Jun 27 '06 #5
Maric Michaud a écrit :
Le mardi 27 juin 2006 05:05, Bruno Desthuilliers a écrit :
import types
t.update = types.MethodTyp e(another_updat e)

This works with :

t.update = types.MethodTyp e(another_updat e, t)


oops ! too fast on the send button :(
And thanks for the correction.
Jun 27 '06 #6

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

Similar topics

2
8558
by: JHB | last post by:
Hi, How can I do a location.replace when I use a form, like when I use a href? This works. <a href="Ny HTML-side20.htm"; method="post" id="frm" name="BrugerHovedSide" onsubmit="location.replace(this.href);" > <input class="ok" type="submit" value="Opfrisk data" id=submit1 name=submit1> </a>
5
11341
by: Mahesha | last post by:
Hello, I need help in replacing one string pattern with another. Ex: I have a financial security expression like log(T 3.25 6/24/2004)/sqrt(T 4.5 6/19/2002) Here "T 3.25 6/24/2004" is a variable on which I need to perform log and then divide the result with 3.980. While parsing such expressions, I need to find all occurence of date values and replace "/" character with "~" character. I need to do this only for date portion of the
3
2399
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 built in a class library that had multithreading enabled.
23
1934
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 = NewClass() newobj.__dict__.update(object.__dict__) return newobj
3
3496
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 read in msdn : and notice that trim only Removes all occurrences of white space characters from the beginning and end of this instance. So what for the middle ? .NET Framework Class Library
10
1901
by: Steven W. Orr | last post by:
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)
10
18624
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 parameter with which you can write wanted character at that position. But no, Replace method only allows replacing one known character with another. The problem is I don't know the character to replace, just must replace the character at a known...
1
3386
by: NvrBst | last post by:
I want to use the .replace() method with the regular expression /^ %VAR % =,($|&)/. The following DOESN'T replace the "^default.aspx=,($|&)" regular expression with "": --------------------------------- myStringVar = myStringVar.replace("^" + iName + "=,($|&)", ""); --------------------------------- The following DOES replace it though: --------------------------------- var match = myStringVar.match("^" + iName + "=,($|&)");
10
1441
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 been created) without adding any overhead to the call of the other object's methods.
0
8233
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8619
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8334
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8474
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7158
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6108
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4173
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2604
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1784
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.