473,406 Members | 2,281 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,406 software developers and data experts.

Adding methods to an object

Hi, there is a way to add methods to an object dynamically? I need to
do something like this. I remember python allowed this ...

class A(object):
def do(s, m):
print m

@staticmethod
def init(obj):
obj.do = A.do

class Test(object):
pass

o = Test()
A.init(o)

o.do(10)

Now it gives me an error ... unbound method ...

tnx, gabriele

Oct 13 '05 #1
3 1910
This isn't code of mine, it's probably from the cookbook, maybe with
little changes:

| def addMethod(object, method, name=None):
| if name is None: name = method.func_name
| class newclass(object.__class__):
| pass
| setattr(newclass, name, method)
| object.__class__ = newclass

name is the name for the new method, if it's None then the name of
"method" is used.

Bye,
bearophile

Oct 13 '05 #2
gabriele,

This works (A, Test, and o as defined by you):
a=A()
o.do(a, 10) 10

Your problem is that do() really has two parameters, an A instance and
whatever you want to print.

Why not do this:
def newdo(m): .... print m
.... newdo(10) 10 o=Test()
o.newdo = newdo
o.newdo(10)

10

Robert

Oct 13 '05 #3
On Thu, 13 Oct 2005 06:06:20 -0700, Gabriele *darkbard* Farina wrote:
Hi, there is a way to add methods to an object dynamically?


Yes. There are three different sorts of methods, and three ways of adding
them.

py> class Parrot:
.... def __init__(self):
.... pass
py> # Parrot is the class.
py> # Parrot() is an instance of the class.

Firstly, you want an ordinary method with a "self" parameter, as if you
had defined it when you created the class.
py> def spam(self):
.... return "Spam comes from %s" % self
....
py> Parrot.spam = spam

Now we try calling it from an instance:

py> Parrot().spam()
'Spam comes from <__main__.Parrot instance at 0xed498fec>'

If you try to call spam direct from the class, it fails:

py> Parrot.spam()
TypeError: unbound method spam() must be called with Parrot instance as
first argument (got nothing instead)

The second way of adding a method is a class method. Class methods don't
know about the instance you call them from, only the class.

py> def fjords(cls):
.... return "I'm pining for the fjords at %s." % cls
....
py> Parrot.fjords = classmethod(fjords)

Now we can call it from either the class or any instance, and get the
exact same result. fjords just can't see the instance, only the class:

py> Parrot.fjords()
"I'm pining for the fjords at __main__.Parrot"
py> Parrot().fjords()
"I'm pining for the fjords at __main__.Parrot"

Lastly, we can add a static method, that doesn't know about either the
class or the instance:

py> def ham():
.... return "Genuine pig product."
....
py> Parrot.ham = staticmethod(ham)
py> Parrot.ham()
'Genuine pig product'
py> Parrot().ham()
'Genuine pig product'

Summary:

If you write the function with a "self" argument, and just add it to the
class, you must call that method using an instance. This is an ordinary
instance method, as if you had created the class with it.

If you write the function with a "cls" argument, you must add it to the
class with a classmethod() call, and then call it from either the class or
an instance. This method cannot access the instance that calls it, only
the class.

If you write the function without a "self" or "cls" argument, you must add
it to the class with a staticmethod() call. This method cannot access
either the class or the instance object.

--
Steven.

Oct 13 '05 #4

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...
2
by: Weston C | last post by:
I'm wondering if it's possible to add a method to the Node and/or Element objects (so they'd subsequently be available to any node/element). I'd assume you could just do something like: ...
2
by: manohar.shankar | last post by:
Hi, I have been searching on this topic for quite sometime and didnt get any answer. Is there a way I can extend/add methods/properties to a C# class during runtime. eg., I have class:...
2
by: newsgroper | last post by:
I have an abstract class with some abstract methods. I created another class that derives from the abstract method. In the derived class I have overridden all the abstract methods. However, I...
8
by: Ed Leafe | last post by:
Here's what I'm trying to do; please let me know if I'm nuts or not. Given a string consisting of the code you would normally define in a class's method, add that compiled code to an instance of...
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...
9
by: Mike | last post by:
I was messing around with adding methods to a class instance at runtime and saw the usual code one finds online for this. All the examples I saw say, of course, to make sure that for your method...
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: Gabriel Genellina | last post by:
En Tue, 29 Jul 2008 01:17:13 -0300, Piyush Anonymous <piyush.subscription@gmail.comescribi�: You forget the self argument (this explains the error you got). It's a lot easier than that;...
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?
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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
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,...
0
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...

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.