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

Adding new methods to new-style classes dynamically

Good day to all.

Some time ago I'd been playing with a framework which uses dynamic
class creation havily. Say, I could do:

class A:
pass

# I method name is dynamic
meth_name = 'foo'

#method code can also be dynamic - any executable object will be good
enough
func = lambda self: self.__class__.__name__

A.__dict__[meth_name] = func
a = A()
print a.foo()
A # methods could be added/changed at runtime, without re-instantination
A.__dict__[meth_name] = lambda self: type(self)
print a.foo() <type 'instance'>
#well, try this with the new-style class
class A(object):
pass

# the new-style __dict__ is a dictproxy object
A.__dict__[meth_name] = lambda self: type(self)Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: object does not support item assignment

Of course, I can do
A.foo = some_executable_object
But that does help when a dynamic method name is needed.
Another option is:
exec('A.%s = %s'%('foo', 'some_executable_option'))
But I don't like eval'ling things :)

Is there other way to add/change methods to new-style classes
dynamically?

Jul 19 '05 #1
4 2350
Do you mean setattr?

setattr(A, meth_name, lambda self: type(self))
Michele Simionato

Jul 19 '05 #2
Max Derkachev wrote:
[snip]
#well, try this with the new-style class
class A(object):
pass

# the new-style __dict__ is a dictproxy object
A.__dict__[meth_name] = lambda self: type(self)
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: object does not support item assignment

Of course, I can do
A.foo = some_executable_object
But that does help when a dynamic method name is needed.
Another option is:
exec('A.%s = %s'%('foo', 'some_executable_option'))
But I don't like eval'ling things :)

Is there other way to add/change methods to new-style classes
dynamically?


Ever considered setattr()? Not only does it appear to do the job but
also it avoids those __make__your__eyes__bleed__ double underscores.
class A(object): .... pass
.... A.__dict__['foo'] = 123 Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object does not support item assignment setattr(A, 'foo', 123)
A.foo 123>> def bar(self): .... print 'bar bar blog ship'
.... setattr(A, 'bar', bar)
eh = A()
eh.bar() bar bar blog ship


HTH,
John

Jul 19 '05 #3

John Machin wrote:
A.foo

123


Oh, I've been a little dumb to forget about it :)
Thanks.

Max.

Jul 19 '05 #4
On Thu, May 05, 2005 at 01:35:09AM -0700, Max Derkachev wrote:
Good day to all.

Some time ago I'd been playing with a framework which uses dynamic
class creation havily. Say, I could do: <snip>
#well, try this with the new-style class
class A(object):
pass

# the new-style __dict__ is a dictproxy object
A.__dict__[meth_name] = lambda self: type(self)
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: object does not support item assignment
Is there other way to add/change methods to new-style classes
dynamically?

import new
dir(new) ['__builtins__', '__doc__', '__file__', '__name__', 'classobj', 'code', 'function', 'instance', 'instancemethod', 'module'] def foo(self): .... print "FOO!" A.foo = new.instancemethod(foo, None, A) # func, object, class
A.foo <unbound method A.foo> a = A()
a.foo <bound method A.foo of <__main__.A object at 0xb7e0b4cc>> a.foo()

FOO!

-jackdied
Jul 19 '05 #5

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

Similar topics

0
by: Dave Benjamin | last post by:
I just noticed that the "new" module is deprecated in Python 2.3. Since the old way of adding a method to a particular instance (not its class) was to use new.instancemethod, I am guessing that we...
7
by: jon | last post by:
I'm trying to add a row to a table and I think I'm not doing something right. The sample code below contains a table with 4 single cell rows, a button and a javascript function that the button...
9
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...
4
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,...
1
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...
47
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...
12
by: Bob Jones | last post by:
I have an odd business requirement and I think that the implementation is not correct in the terms of OOP development. Any help on the concepts would be very appreciated! We currently have a...
1
by: nrasch | last post by:
I am coding an application in VB.Net 2005 where objects of a custom class are saved/retrieved into/out of a DB. As my application moves into its 2nd version I have to add new methods and properties...
7
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...
3
by: zslevi | last post by:
Can I access the class attributes from a method added at runtime? (My experience says no.) I experimented with the following code: class myclass(object): myattr = "myattr" instance =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.