473,799 Members | 3,147 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 1737
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
2354
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
1671
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 what this post is about). I've looked at threads, and the inability to kill them easily was a...
8
2946
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 side effects, and to make the solution as light-weight as possible.
2
7681
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 behavior? <!-- main page --> <html> <head> <script type="text/javascript">
11
2298
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
4434
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 System.EventArgs) Handles btnPlaceBet.Click ' Dim Myds As Footbet.DStable '...
47
3901
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? Are there any problems with adding the ability to have functions
3
2264
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
3392
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 anybody could guide me as which files and
0
9685
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
10470
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10214
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
10023
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
9067
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...
0
6803
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5583
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3751
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2935
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.