473,748 Members | 4,067 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 1680
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
2497
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
1783
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
10901
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
1781
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
1584
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
1994
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
1171
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
1414
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
3387
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
5516
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
8991
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
9372
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
9324
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,...
1
6796
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6074
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
4606
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4874
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3313
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
3
2215
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.