473,699 Members | 2,598 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Adding and modifying methods at run-time

Hi,

I want to add methods to a class instance at run-time based on a base
method, but modify one of the existing ( or add if possible ) params of the
base method. Say a class like this :
class A:
def __init__(self):
self.obj1() # some dummy object having a name attribute
self.obj2() # some dummy object having a name attribute
def __method1__(sel f, param1, param2, param3 = None):
# use some property on param3 in some operations
def addNewMethod(se lf, param1, new_obj):
new_func = copy.copy(self. __method1__)
# modify a copy of self.__method1_ _ and change the param3 to point
new_obj
# and add the method
setattr(self, 'method4%s' % new_obj.name, new_func)

use the class like so :

a = A()
a.addNewMethod( 1, a.obj1)
# use new dynamically method
a.method4obj1(1 ,2) # now the third param with a default is set to point to
obj1 instead of None

I'm crashing at the copy-method in addNewMethod. It crashes with the
exception "TypeError: function() takes at least 2 arguments (0 given)". This
is deep inside the copy-module.

Any hints or clues?

Best regards,
Thomas
Jul 18 '05 #1
2 1677
Thomas Weholt wrote:
a = A()
a.addNewMethod( 1, a.obj1)
# use new dynamically method
a.method4obj1(1 ,2) # now the third param with a default is set to point to
obj1 instead of None

I'm crashing at the copy-method in addNewMethod. It crashes with the
exception "TypeError: function() takes at least 2 arguments (0 given)".
This is deep inside the copy-module.

Any hints or clues?


I have to admit that I'm not fully undestanding what your code above is
supposed to do - but form what I understand you try to introduce a new
method on an object where a certain named parameter is bound to a special
value.

Now this problem can be split into two parts:

1 - create a method that has a paramter bound to a certain value
2 - add that method to an object instance

The first thing is known as currying, and there is a cookbook recipe that
does that very well:

http://aspn.activestate.com/ASPN/Coo...n/Recipe/52549

You will end up with a new method that can be invoked. Now to make this an
instance method, remove the space between the last two words before the
comma in this sentence and look up the result in the python docs :)

Seriously, all you need is the function instancemethod from the module new.
Use it to create a new method on your instance.

The following program illustrates the concepts, the curry-fun is taken from
the recipes comments:

import new

def curry(*args, **create_time_k wds):
func = args[0]
create_time_arg s = args[1:]
def curried_functio n(*call_time_ar gs, **call_time_kwd s):
args = create_time_arg s + call_time_args
kwds = create_time_kwd s.copy()
kwds.update(cal l_time_kwds)
return func(*args, **kwds)
return curried_functio n
class foo:
def method(_, arg1, named_arg=None) :
print (arg1, named_arg)

f = foo()

f.method(1)

new_m = curry(foo.metho d, named_arg="some thing")

new_m(f,2)

f.new_m = new.instancemet hod(new_m, f, foo)

f.new_m(3)


--
Regards,

Diez B. Roggisch
Jul 18 '05 #2
That worked great !!! Thanks alot.

Thomas
"Diez B. Roggisch" <de*********@we b.de> wrote in message
news:c7******** *****@news.t-online.com...
Thomas Weholt wrote:
a = A()
a.addNewMethod( 1, a.obj1)
# use new dynamically method
a.method4obj1(1 ,2) # now the third param with a default is set to point to obj1 instead of None

I'm crashing at the copy-method in addNewMethod. It crashes with the
exception "TypeError: function() takes at least 2 arguments (0 given)".
This is deep inside the copy-module.

Any hints or clues?
I have to admit that I'm not fully undestanding what your code above is
supposed to do - but form what I understand you try to introduce a new
method on an object where a certain named parameter is bound to a special
value.

Now this problem can be split into two parts:

1 - create a method that has a paramter bound to a certain value
2 - add that method to an object instance

The first thing is known as currying, and there is a cookbook recipe that
does that very well:

http://aspn.activestate.com/ASPN/Coo...n/Recipe/52549

You will end up with a new method that can be invoked. Now to make this an
instance method, remove the space between the last two words before the
comma in this sentence and look up the result in the python docs :)

Seriously, all you need is the function instancemethod from the module

new. Use it to create a new method on your instance.

The following program illustrates the concepts, the curry-fun is taken from the recipes comments:

import new

def curry(*args, **create_time_k wds):
func = args[0]
create_time_arg s = args[1:]
def curried_functio n(*call_time_ar gs, **call_time_kwd s):
args = create_time_arg s + call_time_args
kwds = create_time_kwd s.copy()
kwds.update(cal l_time_kwds)
return func(*args, **kwds)
return curried_functio n
class foo:
def method(_, arg1, named_arg=None) :
print (arg1, named_arg)

f = foo()

f.method(1)

new_m = curry(foo.metho d, named_arg="some thing")

new_m(f,2)

f.new_m = new.instancemet hod(new_m, f, foo)

f.new_m(3)


--
Regards,

Diez B. Roggisch

Jul 18 '05 #3

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

Similar topics

15
2493
by: Paul Paterson | last post by:
I am trying to find a way to mimic by-reference argument passing for immutables in Python. I need to do this because I am writing an automated VB to Python converter. Here's an example of the VB code: Sub Change(ByVal x, ByRef y) x = x+1 y = y+1 End Sub
7
1778
by: Jan Gregor | last post by:
Hello folks I want to apply changes in my source code without stopping jython and JVM. Preferable are modifications directly to instances of classes. My application is a desktop app using swing library. Python solutions also interest me. Solution similiar to "lisp way" is ideal.
9
10897
by: Ben Dewey | last post by:
Project: ---------------------------- I am creating a HTTPS File Transfer App using ASP.NET and C#. I am utilizing ActiveDirectory and windows security to manage the permissions. Why reinvent the wheel, right? Everything so far is working well with the Active Directory. The problem I am having is with adding File Permissions to a directory. I am currently using some code courtesy of "Willy Denoyette "
4
1775
by: paul | last post by:
Hi, Im trying to add a dataset to the app_code directory using vs2005 \ SQL2005 beta 2. When I run through the wizard I select the option to auto create new Stored Procedures (Select, update, delete, insert commands) after already specifying a very basic select command that consists of two fields. All procedures are created fine and i'm able to save the xsd file. Then I create a new gridview in which i use the xsd file object as my
1
1578
by: Jeff Dillon | last post by:
I'm using the webservice I've created: http://www.emergencyreporting.com/ERSWebService/ERSDispatch.asmx When building a client VB.NET app, and adding a web reference to the above file, I see that the client is creating extra methods. For my IncidentOpen method, the client is adding methods like BeginIncidentOpen and EndIncidentOpen. This is not an async web service, is there a corresponding web service setting I need to set so these...
3
1993
by: _DS | last post by:
The two obvious methods for ref'ing assemblies are: Add a reference and 'Browse' for the actual DLL OR Add existing project to the solution, then add a ref to 'Project'. 1: I'd like to find out what the latter method is doing. I'm assuming that it makes sure that debug exe gets matched to
3
1169
by: Kenneth McDonald | last post by:
This is possible with pure Python classes. Just add the method as new attribute of the class. However, that won't work for the builtins. I know that this is somewhat dangerous, and also that I could subclass the builtins, but not being able to do things like ''.length drives me a little nuts. Python is about the only computer language I use, and I think it's certainly the best of the scripting languages, but there are inconsistencies in...
2
1409
by: Jay Balapa | last post by:
Hello, We have a webservice which is called by our pocket pc apps. We have a need to filter data, so we want to add a another method on top to the existing method. Existing Service.asmx Sync(DataSet myDataset) New Service.asmx Sync(DataSet myDataset);
7
3384
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
4
5514
by: ifitzgerald | last post by:
Hi, I am modifying a rather large and complex MFC application (written by someone else) written in Visual C++ 6.0 with service pack 6. I need to add serial communication functionality to the program, and since I am very familiar with the Microsoft Comm Control from Visual Basic I decided that I would use that in this application. To make things easier on myself, I decided to make several test applications using the MS Comm control in VC++...
0
8687
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
8617
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9174
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...
0
9035
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
8914
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
7751
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
5875
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();...
1
3057
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
2
2347
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.