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

Re: Dynamically adding methods to a class...

En Tue, 29 Jul 2008 01:17:13 -0300, Piyush Anonymous
<pi*****************@gmail.comescribi�:
class MyObject:
def __init__(self, name):
self.name = name

def do_this_default(self):
print "default do_this implementation for %s" % self.name

def custom_do_this(): #method to be added
print "custom do_this implementation for %s" % self.name
You forget the self argument (this explains the error you got).
def funcToMethod(func,clas,method_name=None):
"""Adds func to class so it is an accessible method; use method_name
to
specify the name to be used for calling the method.
The new method is accessible to any instance immediately."""
import new
method = new.instancemethod(func,None,clas)
print method
if not method_name: method_name=func.__name__
clas.__dict__[method_name]=func
It's a lot easier than that; just add the *function* object to the class
namespace:
setattr(clas, method_name, func)
If you know the name when you write the code, just set the attribute:

pyo = MyObject("hello")
pyMyObject.custom_do_this = custom_do_this
pyo.custom_do_this()
custom do_this implementation for hello

new.instancemethod is useful to add specific methods to individual
instances, but it's not used to add methods globally to the class.
Error I am getting;
TypeError: custom_do_this() takes no arguments (1 given)
Add the self argument and you're done.
Why am I getting it?

Also how can I do this in new style class (inherited from 'object')?
It's the same thing, no difference.

--
Gabriel Genellina

Jul 30 '08 #1
0 1081

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

Similar topics

5
by: damian birchler | last post by:
Hello there! I'm wondering if it is possible to automatically dynamically add methods to a class instance. For example, if there is a class Foo with one method named add_function and an...
4
by: Max Derkachev | last post by:
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'
7
by: Luc Tremblay | last post by:
Given the typical following code: void Listener::HandleEvent(const Event& event) { // handling code } In a "clean" fashion, how is it possible to add custom data (to be subsequently...
5
by: Sarir Khamsi | last post by:
I have a class (Command) that derives from cmd.Cmd and I want to add methods to it dynamically. I've added a do_alias() method and it would be nice if I could turn an alias command into a real...
8
by: Kevin Little | last post by:
#!/usr/bin/env python ''' I want to dynamically add or replace bound methods in a class. I want the modifications to be immediately effective across all instances, whether created before or...
11
by: Steven D'Aprano | last post by:
Suppose I create a class with some methods: py> class C: .... def spam(self, x): .... print "spam " * x .... def ham(self, x): .... print "ham * %s" % x .......
5
by: Nathan Harmston | last post by:
Hi, Sorry if the subject line of post is wrong, but I think that is what this is called. I want to create objects with class Coconuts(object): def __init__(self, a, b, *args, **kwargs):...
8
by: =?Utf-8?B?U2hhd24=?= | last post by:
Hi; i just started research reflection and i'm wondering if i have an empty class file can i use reflection to add member variables and attributes dynamically and then instantiate the class? What...
5
by: akonsu | last post by:
hello, i need to add properties to instances dynamically during run time. this is because their names are determined by the database contents. so far i found a way to add methods on demand: ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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...
0
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...

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.