473,763 Members | 1,377 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Adding method to a class on the fly

Hi list,

I have a need to create class methods on the fly. For example, if I
do:

class Dummy:
def __init__(self):
exec '''def method_dynamic( self):\n\tretur n
self.method_sta tic("it's me")'''
return

def method_static(s elf, text):
print text
return

I like that to be the same as:

class Dummy:
def __init__(self):
return

def method_dynamic( self):
return self.method_sta tic("it's me")

def method_static(s elf, text):
print text
return

so that I can do:

dum=Dummy.metho d_dynamic()

and see "it's me" printed.

Can that be done?

Thanks,

Jun 22 '07 #1
21 2387
Found a message on the web that says I need to use setattr to add the
method to the class at run time. But how do I do that?

Regards,

On Jun 22, 12:02 pm, John Henry <john106he...@h otmail.comwrote :
Hi list,

I have a need to create class methods on the fly. For example, if I
do:

class Dummy:
def __init__(self):
exec '''def method_dynamic( self):\n\tretur n
self.method_sta tic("it's me")'''
return

def method_static(s elf, text):
print text
return

I like that to be the same as:

class Dummy:
def __init__(self):
return

def method_dynamic( self):
return self.method_sta tic("it's me")

def method_static(s elf, text):
print text
return

so that I can do:

dum=Dummy.metho d_dynamic()

and see "it's me" printed.

Can that be done?

Thanks,

Jun 22 '07 #2
On Jun 22, 3:02 pm, John Henry <john106he...@h otmail.comwrote :
Hi list,

I have a need to create class methods on the fly. For example, if I
do:

class Dummy:
def __init__(self):
exec '''def method_dynamic( self):\n\tretur n
self.method_sta tic("it's me")'''
return

def method_static(s elf, text):
print text
return

I like that to be the same as:

class Dummy:
def __init__(self):
return

def method_dynamic( self):
return self.method_sta tic("it's me")

def method_static(s elf, text):
print text
return

so that I can do:

dum=Dummy.metho d_dynamic()

and see "it's me" printed.

Can that be done?

Thanks,
class Dummy:
def method(self, arg):
print arg

def method2(self, arg):
self.method(arg )

Dummy.method2 = method2
Dummy.method2(' Hello, world!')

Jun 22 '07 #3
On Jun 22, 2:24 pm, askel <dummy...@mail. ruwrote:
class Dummy:
def method(self, arg):
print arg

def method2(self, arg):
self.method(arg )

Dummy.method2 = method2
Dummy.method2(' Hello, world!')
Traceback (most recent call last):
File "test1.py", line 8, in ?
Dummy.method2(' Hello, world!')
TypeError: unbound method method2() must be called with Dummy instance
as first argument (got str instance
instead)
>I like that to be the same as:

class Dummy:
def __init__(self):
return

def method_dynamic( self):
return self.method_sta tic("it's me")

def method_static(s elf, text):
print text
return
so that I can do:

dum=Dummy.meth od_dynamic()

and see "it's me" printed.
When are you able to see that?

Jun 22 '07 #4
On Jun 22, 5:17 pm, 7stud <bbxx789_0...@y ahoo.comwrote:
On Jun 22, 2:24 pm, askel <dummy...@mail. ruwrote:
class Dummy:
def method(self, arg):
print arg
def method2(self, arg):
self.method(arg )
Dummy.method2 = method2
Dummy.method2(' Hello, world!')

Traceback (most recent call last):
File "test1.py", line 8, in ?
Dummy.method2(' Hello, world!')
TypeError: unbound method method2() must be called with Dummy instance
as first argument (got str instance
instead)
I like that to be the same as:
class Dummy:
def __init__(self):
return
def method_dynamic( self):
return self.method_sta tic("it's me")
def method_static(s elf, text):
print text
return
so that I can do:
dum=Dummy.metho d_dynamic()
and see "it's me" printed.

When are you able to see that?
sorry, of course last line should be:
Dummy().method2 ('Hello, world!')

Jun 22 '07 #5
On Jun 22, 3:23 pm, askel <dummy...@mail. ruwrote:
sorry, of course last line should be:
Dummy().method2 ('Hello, world!')
...which doesn't meet the op's requirements.

Jun 22 '07 #6
On Jun 22, 5:17 pm, 7stud <bbxx789_0...@y ahoo.comwrote:
On Jun 22, 2:24 pm, askel <dummy...@mail. ruwrote:
class Dummy:
def method(self, arg):
print arg
def method2(self, arg):
self.method(arg )
Dummy.method2 = method2
Dummy.method2(' Hello, world!')

Traceback (most recent call last):
File "test1.py", line 8, in ?
Dummy.method2(' Hello, world!')
TypeError: unbound method method2() must be called with Dummy instance
as first argument (got str instance
instead)
I like that to be the same as:
class Dummy:
def __init__(self):
return
def method_dynamic( self):
return self.method_sta tic("it's me")
def method_static(s elf, text):
print text
return
so that I can do:
dum=Dummy.metho d_dynamic()
and see "it's me" printed.

When are you able to see that?
there is no way to call instance method from static one. but in your
case you can make something like:

class Dummy:
@staticmethod
def method(arg):
print arg

def method2(arg):
Dummy.method(ar g)

Dummy.method2 = staticmethod(me thod2)
Dummy.method2(' Hello, world!')

- OR -

def method2(cls, arg):
cls.method(arg)

Dummy.method2 = classmethod(met hod2)
Dummy.method2(' Hello, world!')

Jun 22 '07 #7
On Jun 22, 2:28 pm, askel <dummy...@mail. ruwrote:
On Jun 22, 5:17 pm, 7stud <bbxx789_0...@y ahoo.comwrote:
On Jun 22, 2:24 pm, askel <dummy...@mail. ruwrote:
class Dummy:
def method(self, arg):
print arg
def method2(self, arg):
self.method(arg )
Dummy.method2 = method2
Dummy.method2(' Hello, world!')
Traceback (most recent call last):
File "test1.py", line 8, in ?
Dummy.method2(' Hello, world!')
TypeError: unbound method method2() must be called with Dummy instance
as first argument (got str instance
instead)
>I like that to be the same as:
>class Dummy:
def __init__(self):
return
def method_dynamic( self):
return self.method_sta tic("it's me")
def method_static(s elf, text):
print text
return
>so that I can do:
>dum=Dummy.meth od_dynamic()
>and see "it's me" printed.
When are you able to see that?

there is no way to call instance method from static one. but in your
case you can make something like:

class Dummy:
@staticmethod
def method(arg):
print arg

def method2(arg):
Dummy.method(ar g)

Dummy.method2 = staticmethod(me thod2)
Dummy.method2(' Hello, world!')

- OR -

def method2(cls, arg):
cls.method(arg)

Dummy.method2 = classmethod(met hod2)
Dummy.method2(' Hello, world!')


Thanks for the response.

The above doesn't exactly do I what need. I was looking for a way to
add method to a class at run time.

What does work, is to define an entire sub-class at run time. Like:

class DummyParent:
def __init__(self):
return

def method_static(s elf, text):
print text
return

text = "class Dummy(DummyPare nt):"
text += "\n\t" + "def __init(self):"
text += "\n\t" + "\tDummyParent. __init__(self)"
text += "\n\t" + "def method_dynamic( self):"
text += "\n\t" + "\tself.method_ static(\"it's me\")"

exec text

dum=Dummy().met hod_dynamic()
Thanks again.

Jun 22 '07 #8
On Jun 22, 2:44 pm, John Henry <john106he...@h otmail.comwrote :
On Jun 22, 2:28 pm, askel <dummy...@mail. ruwrote:
(snipped)
>
The above doesn't exactly do I what need. I was looking for a way to
add method to a class at run time.

I'm not sure what you mean by this. Bind an attribute -- a method --
to class Dummy if and only if an instance of this class is created?
What does work, is to define an entire sub-class at run time. Like:

class DummyParent:
def __init__(self):
return

def method_static(s elf, text):
print text
return

text = "class Dummy(DummyPare nt):"
text += "\n\t" + "def __init(self):"
text += "\n\t" + "\tDummyParent. __init__(self)"
text += "\n\t" + "def method_dynamic( self):"
text += "\n\t" + "\tself.method_ static(\"it's me\")"

exec text

dum=Dummy().met hod_dynamic()

Thanks again.

I tend to avoid exec if possible. Also, you
seem to be a bit inexact with regard to the
term "static".
class Dummy(object):
def __init__(self):
new_method_name = 'method_dynamic '
try:
getattr(Dummy, new_method_name )
except AttributeError:
print "Creating an instance method..."
def newf(self):
"""Somethin g Descriptive Here"""
return self.method_sta tic("it's me")
newf.__name__ = new_method_name
setattr(Dummy, new_method_name , newf)
def method_static(s elf, text):
"""I hate this name. Do not confuse this with a staticmethod;
what you probably meant was that this is an attribute (a
method)
bound within the class body as opposed to elsewhere"""
print text
return # is this necessary?

d1 = Dummy()
d1.method_dynam ic()
d2 = Dummy()
d2.method_dynam ic()
print d1.method_dynam ic.im_func.__na me__
print d1.method_dynam ic.im_func.__di ct__
print d1.method_dynam ic.im_func.__do c__
print d1.method_dynam ic.im_func.__mo dule__
print d1.method_dynam ic.im_self

--
Hope this helps,
Steven

Jun 22 '07 #9
7stud wrote:
On Jun 22, 3:23 pm, askel <dummy...@mail. ruwrote:
>>sorry, of course last line should be:
Dummy().metho d2('Hello, world!')


..which doesn't meet the op's requirements.
Which were contradictory.
Jun 23 '07 #10

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

Similar topics

8
1389
by: Thomas Guettler | last post by:
Hi! How can I add a method to an object. This code does not work: class Foo: def __init__(self): self.counter=0 f=Foo()
0
1137
by: Federico Caselli | last post by:
Hi, Im using Visual basic.NET and adding a .cs file in my project (that contains myCsClass class in MyNameSpace namespace), I can't see myCsClass in the Visual Studio class explorer. Obvously, I need to instantiate MyCsClass in my visual basic class, and I don't know how to reference or import it. Thank you
5
5921
by: surrealtrauma | last post by:
the requirement is : Create a class called Rational (rational.h) for performing arithmetic with fractions. Write a program to test your class. Use Integer variables to represent the private data of the class – the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it is declared. The constructor should contain default values in case no initializers are provided and should...
3
2069
by: Casper | last post by:
Hi .Net experts, I am trying to build a user control of textbox and would like to add a public method to the object like public void CheckOptions(string str) { // codes here }
0
925
by: Ye | last post by:
I have a problem adding a class Wizard in .Net after I add a dialoge in the class. As somebody suggested, I tried to add stdafx.h as a member of the project (using add existing item) and then try to add the class, and still did not work. Anybody have an idea? Thanks in advance.
0
836
by: Alex | last post by:
Hi, all I'm writing my first project under VS8 in MC++. I would like to create some helper class, which will provide communication with the SQL Server through ADO.NET. I'm thinking of reusing it in some other projects. So I go Add -> Class, select C++, and then I'm having the problem picking the base class. I thought, that I always can select Object (System.Object), but when I click Finish, I'm getting the
4
1821
by: marek.rocki | last post by:
First of all, please don't flame me immediately. I did browse archives and didn't see any solution to my problem. Assume I want to add a method to an object at runtime. Yes, to an object, not a class - because changing a class would have global effects and I want to alter a particular object only. The following approach fails: class kla: x = 1
3
1641
by: raylopez99 | last post by:
Oh, I know, I should have provided complete code in console mode form. But for the rest of you (sorry Jon, just kidding) I have an example of why, once again, you must pick the correct entry point in your code when adding a class (oops, I meant variable, or instantiation of a object that's a class) to a form constructor. Specifically, adding a class variable should always come BEFORE the statement "InitializeComponent()" in your form...
0
9563
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
9386
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
9998
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
9938
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
9822
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8822
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
7366
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...
3
3523
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2793
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.