473,556 Members | 2,420 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Adding functions to an existing instance

I need a way to add a method to an existing instance, but be as close as
possible to normal instance methods. Using 'new' module or such code as
'def addfunc(...): def helper(...) .. setattr(...)' causes a cyclic
reference which requires using 'gc.collect' to release the object. Also
'new' is deprecated. I also made a helper that uses weakref, but the
problem is when the object is gone, existing instance method object
would not work:
f = myobject.functi on
myobject = None
f() <--- would not work if it holds weak ref to myobject
The best I can come up with is to create a parent class and try to
simulate as best as possible. The code below works with no cyclic
references that would be cause by 'new.instanceme thod' etc, and without
the weakref as well. Is there a simpler way of achieving the same
without cyclic references? I know this is 'monkey patching' but for a
small project I'm working on it is useful to be able to add functions
dynamically to one instance without adding it to another instance of the
same class, etc.
class InstanceFunctio nHelper(object) :
class FunctionCaller( object):
def __init__(self, instance, func):
self.__instance = instance
self.__func = func

def __call__(self, *args, **kwargs):
return self.__func(sel f.__instance, *args, **kwargs)

def add_instance_fu nction(self, func, name = None):
if name is None:
name = func.__name__

if hasattr(self, name):
delattr(self, name)

try:
self._instance_ funcs[name] = func
except AttributeError:
self._instance_ funcs = {name: func}

def __setattr__(sel f, name, value):
funcs = getattr(self, '_instance_func s', None)
if funcs and name in funcs:
del funcs[name]

object.__setatt r__(self, name, value)

def __delattr__(sel f, name):
funcs = getattr(self, '_instance_func s', None)
if funcs and name in funcs:
del funcs[name]
else:
object.__delatt r__(self, name)

def __getattr__(sel f, name):
if name == '_instance_func s':
raise AttributeError

funcs = object.__getatt ribute__(self, '_instance_func s')

if name in funcs:
return InstanceFunctio nHelper.Functio nCaller(self, funcs[name])

raise AttributeError

x = 0
class Blah(InstanceFu nctionHelper):
def __init__(self):
global x
x += 1
def __del__(self):
global x
x -= 1

def Action(self, value):
print self
print value

a = Blah()
a.add_instance_ function(Action )
a.Action(5)
a = None
print x

Jun 27 '08 #1
1 1725
On 26 juin, 17:18, Allen <brian_vanderbu ...@yahoo.comwr ote:
I need a way to add a method to an existing instance, but be as close as
possible to normal instance methods.
def set_method(obj, func, name=None):
if not name:
name = func.__name__
setattr(obj, name, func.__get__(ob j, type(obj)))

class Toto(object):
pass

toto = Toto()

def titi(self):
print self

set_method(toto , titi)

Jun 27 '08 #2

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

Similar topics

0
2331
by: Anthony Baxter | last post by:
To go along with the 2.4a3 release, here's an updated version of the decorator PEP. It describes the state of decorators as they are in 2.4a3. PEP: 318 Title: Decorators for Functions and Methods Version: $Revision: 1.34 $ Last-Modified: $Date: 2004/09/03 09:32:50 $ Author: Kevin D. Smith, Jim Jewett, Skip Montanaro, Anthony Baxter
4
1658
by: Rhamphoryncus | last post by:
First a bit about myself. I've been programming in python several years now, and I've got several more years before that with C. I've got a lot of interest in the more theoretical stuff (language design, component architectures, etc). Of late my focus has been on concurrent operations (and on how to design a GUI architecture, but that's not...
8
2931
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 after the class was modified. I need this to work for both old ('classic') and new style classes, at both 2.3 and 2.4. I of course want to avoid...
2
7665
by: laredotornado | last post by:
Hello, I am looking for a cross-browser way (Firefox 1+, IE 5.5+) to have my Javascript function execute from the BODY's "onload" method, but if there is already an onload method defined, I would like mine to run immediately after it. So in the code below, what JS would i need to add to my "myfile.inc" page so that I could guarantee this...
11
2278
by: Steven D'Aprano | last post by:
Suppose I create a class with some methods: py> class C: .... def spam(self, x): .... print "spam " * x .... def ham(self, x): .... print "ham * %s" % x .... py> C().spam(3) spam spam spam
6
4402
by: Rudy | last post by:
Hi all, I know this is easy, just can't seem to get it. I have a windows form, and a text box, with a value already in it. I need to add that value to a table. It's just one value, so the entire row doesn't get filled. I have a connection and all that stuff. Private Sub btnPlaceBet_Click(ByVal sender As System.Object, ByVal e As...
47
3842
by: Albert | last post by:
So structures are useful to group variables, so you can to refer to a collection as a single entity. Wouldn't it be useful to also have the ability to collect variable and functions? Ask K&R say, C programs consist of variables to store the input and functions to manipulate them. This would make C object-oriented - how cool would that be?...
3
2257
by: jjk1407 | last post by:
hello, i am a newbie to vb.net. i met a problem with vb on adding function to an existing class. when i was trying to add a function, say myfunc, to a class, myclass,
7
3380
by: Maximus Decimus | last post by:
HI all, I am using python v2.5 and I am an amateur working on python. I am extending python for my research work and would like some help and guidance w.r.t this matter from you experienced python developers. II want to add some more KEYWORDS and DATATYPES into the python script apart from the existing ones. It would be really great if...
0
7622
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...
0
7547
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7825
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8060
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...
1
7588
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...
0
5171
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3596
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1159
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
865
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.