473,386 Members | 1,860 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,386 software developers and data experts.

Dynamically adding methods to objects?

Hello there!

I'm wondering if it is possible to automatically dynamically add
methods to a class instance. For example, if there is a class Foo with
one method named
add_function and an instance of Foo f -

class Foo:
add_function(self, name, args):
# ...
# ...

f = Foo()

-, could one add arbitrary methods to f calling its method
add_function?

I know how to do it manually, I just define a function and assigne it
to f -

def bar():
pass

f.bar = bar -,
but what if this should be done at runtime. How can I get the string
passed to f.add_function as name to be the name of a new function in
the function's definiton?

Thanks a lot
Jul 18 '05 #1
5 1475


damian birchler wrote:
I know how to do it manually, I just define a function and assigne it
to f -

def bar():
pass

f.bar = bar -,
but what if this should be done at runtime. How can I get the string
passed to f.add_function as name to be the name of a new function in
the function's definiton?


f.bar = bar is the same as setattr (f, "bar", bar)

Remember that bar does not become a method of f, but remains
only a function which is stored in f. Is not subject of the
binding of the "self" parameter.

Greetings,

Holger

Jul 18 '05 #2

"Holger Türk" <ht**@gmx.de> wrote in message
news:c9*************@news.t-online.com...


damian birchler wrote:
I know how to do it manually, I just define a function and assigne it
to f -

def bar():
pass

f.bar = bar -,
but what if this should be done at runtime. How can I get the string
passed to f.add_function as name to be the name of a new function in
the function's definiton?
f.bar = bar is the same as setattr (f, "bar", bar)

Remember that bar does not become a method of f, but remains
only a function which is stored in f. Is not subject of the
binding of the "self" parameter.


Ah, but that's what I want to do - have a ***method***
where the self parameter works the way I expect it to.

John Roth
Greetings,

Holger

Jul 18 '05 #3
John Roth wrote:
"Holger T?rk" <ht**@gmx.de> wrote in message
news:c9*************@news.t-online.com...
damian birchler wrote:
> I know how to do it manually, I just define a function and assigne it
> to f -
>
> def bar():
> pass
>
> f.bar = bar -,
> but what if this should be done at runtime. How can I get the string
> passed to f.add_function as name to be the name of a new function in
> the function's definiton?


f.bar = bar is the same as setattr (f, "bar", bar)

Remember that bar does not become a method of f, but remains
only a function which is stored in f. Is not subject of the
binding of the "self" parameter.


Ah, but that's what I want to do - have a ***method***
where the self parameter works the way I expect it to.

Is this what you want?

def selfize(obj,func):
def callfunc(*args,**kwargs):
func(obj,*args,**kwargs)
return callfunc

f.bar = withself(f,bar)
--
CARL BANKS http://www.aerojockey.com/software
"If you believe in yourself, drink your school, stay on drugs, and
don't do milk, you can get work."
-- Parody of Mr. T from a Robert Smigel Cartoon
Jul 18 '05 #4
damian birchler wrote:
I'm wondering if it is possible to automatically dynamically add
methods to a class instance.


Try something like this:

import new

class Foo(object):
def add_method(self, name, prints):
"""Add a method to the class which prints a string.

Arguments:
name - the name of the method
prints - the string the method should print
"""
def method(self):
print prints

method = new.instancemethod(method, self, Foo)
setattr(self, name, method)

instance = Foo()
instance.add_method('foo', 'I am foo. Fear me!')
instance.add_method('bar', "I am the humble bar. Please don't hurt me.")
instance.foo()
instance.bar()
Jul 18 '05 #5
Carl Banks <im*****@aerojockey.invalid> writes:
John Roth wrote:
"Holger T?rk" <ht**@gmx.de> wrote in message
news:c9*************@news.t-online.com...
damian birchler wrote:
[ f = Foo() ]
> I know how to do it manually, I just define a function and assigne it
> to f -
>
> def bar():
> pass
>
> f.bar = bar -,
> but what if this should be done at runtime. How can I get the string
> passed to f.add_function as name to be the name of a new function in
> the function's definiton?

f.bar = bar is the same as setattr (f, "bar", bar)

Remember that bar does not become a method of f, but remains
only a function which is stored in f. Is not subject of the
binding of the "self" parameter.


Ah, but that's what I want to do - have a ***method***
where the self parameter works the way I expect it to.

Is this what you want?

def selfize(obj,func):
def callfunc(*args,**kwargs):
func(obj,*args,**kwargs)
return callfunc

f.bar = withself(f,bar)


What's "withself" ?

Isn't John saying he wants exactly what the instancemethod function in
the new module was designed for:

import new
f.bar = new.instancemethod(bar, f, Foo)
?
Jul 18 '05 #6

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

Similar topics

10
by: Richard A. DeVenezia | last post by:
At line this.timerId = setInterval (function(){this.step()}, 100) I get error dialog Error:Object doesn't support this property or method. If I change it to this.timerId = setInterval...
8
by: cool2005 | last post by:
I tried to dynamically add/clone a <tr> from an existing <tr> to a <table> but the problem is that I need to have a "onclick" event handler in the <tr>. I have tried following A. approach...
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...
11
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 .......
0
by: MIGUEL | last post by:
Hi all! Be patient because what I'm going to explain all of you it's more than very strange. I've developed a webservice project that contains two classes. One of them is going to act as a...
7
by: Ron Goral | last post by:
Hello I am new to creating objects in javascript, so please no flames about my coding style. =) I am trying to create an object that will represent a "div" element as a menu. I have written...
12
by: vbnewbie | last post by:
I am having problems accessing properties of dynamically generated objects in VB2005. Can someone please help? In a nutshell: My app creates an equal number of checkboxes and labels that share the...
10
by: Jess | last post by:
Hello, I have a program that stores dynamically created objects into a vector. #include<iostream> #include<vector> using namespace std;
29
by: Quarco | last post by:
This one is driving me nuts.... var tbl = document.createElement("table"); var tbody = document.createElement("tbody"); for(var i=0; i<10; i++) { var row =...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...

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.