473,327 Members | 2,065 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

How to bound a method to a instance ?

Hi,
I would like to know how to bound a method to a instance of a class.

One application would be to allow a change in a method after a reload :

module toto :
--------------
class toto:
def method(self):
(...)
main module :
--------------
import toto

a = toto.toto()
a.method() -> does something ...

reload (toto)
now a is not reloaded...

a.method = toto.toto().method
does not work, because a.method would be bounded to a new instance...
Thanks,

Emmanuel...

Jul 18 '05 #1
5 1808
Emmanuel wrote:
main module :
--------------
import toto

a = toto.toto()
a.method() -> does something ...

reload (toto)
now a is not reloaded...

a.method = toto.toto().method
does not work, because a.method would be bounded to a new instance...


It might be best to change the class of a:

reload (toto)
a.__class__ = toto.toto

Then, a.method will automatically become the new method. Of course,
this will also change all other methods of toto, not just method.

If you really want to change only method, you could do

a.__class__.__dict__['method'] = toto.toto.__dict__['method']

That would change just method, but of all instances of the old
definition of toto.toto.

If you really want to change only one method, and only of one
object, you need to use new.instancemethod:

a.method = new.instancemethod(toto.toto.method.im_func, a, a.__class__)

Regards,
Martin

Jul 18 '05 #2
Wonderfull !!

I thank you very much for this clear explanation...

Emmanuel

=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?= a écrit :
Emmanuel wrote:
main module :
--------------
import toto

a = toto.toto()
a.method() -> does something ...

reload (toto)
now a is not reloaded...

a.method = toto.toto().method
does not work, because a.method would be bounded to a new instance...


It might be best to change the class of a:

reload (toto)
a.__class__ = toto.toto

Then, a.method will automatically become the new method. Of course,
this will also change all other methods of toto, not just method.

If you really want to change only method, you could do

a.__class__.__dict__['method'] = toto.toto.__dict__['method']

That would change just method, but of all instances of the old
definition of toto.toto.

If you really want to change only one method, and only of one
object, you need to use new.instancemethod:

a.method = new.instancemethod(toto.toto.method.im_func, a, a.__class__)

Regards,
Martin


Jul 18 '05 #3
"Martin v. Löwis" wrote:
Emmanuel wrote:
main module :
--------------
import toto

a = toto.toto()
a.method() -> does something ...

reload (toto)
now a is not reloaded...

a.method = toto.toto().method
does not work, because a.method would be bounded to a new instance...


It might be best to change the class of a:

reload (toto)
a.__class__ = toto.toto


Thank you emmanuel for asking this question, I was wondering exactly the
same thing. Is it also possible to override the reload method to make it
(besides reloading) to scan through all namespaces for objects of class
toto.toto and replace their methods automatically? What would that code
look like?

Thanks,

Maarten

--
================================================== =================
Maarten van Reeuwijk Thermal and Fluids Sciences
Phd student dept. of Multiscale Physics
www.ws.tn.tudelft.nl Delft University of Technology
Jul 18 '05 #4
Maarten van Reeuwijk wrote:
Thank you emmanuel for asking this question, I was wondering exactly the
same thing. Is it also possible to override the reload method to make it
(besides reloading) to scan through all namespaces for objects of class
toto.toto and replace their methods automatically? What would that code
look like?


In general, it is impossible or atleast very inefficient to do that.
It may be easiest if toto.toto would prepare itself for reloading:

import weakref
try:
weakref.totos
except AttributeError:
weakref.totos = []

class toto:
def __init__(self, args):
weakref.totos.append(weakref.ref(self))
...

def update_totos():
for t in weakref.totos:
t = t()
if t: t.__class__ = toto

def shrink_totos():
totos = []
for t in weakref.totos:
if t(): totos.append(t)
weakref.totos=[]

Then, after reloading toto, invoke toto.update_totos(). From
time to time, invoke weakref.shrink_totos(), to discard unused
weak references.

If you absolutely want to update all objects without preparing
a list earlier, you can use gc.get_objects() to find all containers;
you need to find out which of those are totos. Don't compare the
classes of the objects for identity (o.__class__ is toto.toto), unless
you have a reference of the old class (i.e. before reloading).

Regards,
Martin

Jul 18 '05 #5
> def shrink_totos():
totos = []
for t in weakref.totos:
if t(): totos.append(t)
weakref.totos=[]

^^ should be totos

- Josiah
Jul 18 '05 #6

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

Similar topics

3
by: Kylotan | last post by:
Although I see lots of references to them in various documentation, I can't find a decent explanation of exactly what they are. I'm guessing that it's a reference to a method that remembers which...
12
by: Russell E. Owen | last post by:
I have several situations in my code where I want a unique identifier for a method of some object (I think this is called a bound method). I want this id to be both unique to that method and also...
0
by: Carlos | last post by:
Hi! I want to instrumentate a class with a number of getter/setters. Each pair of getter/setter must keep it's own state gsState but also access to the state iState of instances of the...
8
by: Kevin Little | last post by:
#!/usr/bin/env python ''' I want to dynamically add or replace bound methods in a class. I want the modifications to be immediately effective across all instances, whether created before or...
19
by: James Fortune | last post by:
I have a lot of respect for David Fenton and Allen Browne, but I don't understand why people who know how to write code to completely replace a front end do not write something that will automate...
1
by: Daniel | last post by:
How do I call a delegate in late bound C# dll? there some way to do this w/ a sharedinterface file? any examples? i tried this but it doesnt work: (oType.GetMethod("IOCTLJOB").Invoke(pObj, new...
6
by: Ron Garret | last post by:
If I do this: def f(self): print self class c1: pass setattr(c1, 'm1', f) Then f is automagically transmogrified into the appropriate sort of method depending on how it is used:
14
by: 7stud | last post by:
Here is some example code that produces an error: class Test(object): def greet(): print "Hello" t = Test() t.greet() TypeError: greet() takes no arguments (1 given)
11
by: Mathias Panzenboeck | last post by:
Hi. I have a problem with weak refs and bound methods. The best explanation for the problem is a short bit of code. I have the three classes Wrapper, Foo and Bar: import weakref class...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.