473,769 Members | 3,350 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 "<interacti ve 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_executabl e_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 2374
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 "<interacti ve 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_executabl e_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__e yes__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 "<interacti ve 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.instancemet hod(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
1318
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 are now supposed to use types.MethodType. Is this the preferred idiom for adding an instance method? import new import types class Test(object): def __init__(self, x):
7
1909
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 runs. In Netscape 7.0 and Firefox 0.8 the code below does add a row to the table when the button is clicked but the alert() shows 4 instead of 5 like I'd expect. Any idea why?
9
10904
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
1585
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...
47
3893
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
12
1601
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 custom Page object which is derived from the base Page object. We also have custom controls that derive from a base class that performs custom drawing and inherits from our own IOurControl interface. There is also a special caching layer in the mix...
1
1255
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 into my custom class. How does one go about adding new methods and/or properties to a custom class and then updating existing objects of that class w/out breaking everything? Ex: Pull existing object from DB -> Convert to new version of...
7
3390
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
3
4078
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 = myclass() def method(x):
0
9590
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
9424
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
10051
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
10000
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
8879
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...
1
7413
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
6675
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
5310
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...
3
2815
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.