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

Adding instance mthods

Hi,

This sort of code works for staticmethods, but fails with instance methods.
Why does it fail? O:-)

class C (object): def g(x,y):
print 'static g', x, y
g = staticmethod(g)
def h(self, x,y): return x+y
C.h = h
dir(C) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
'__hash__', '__init__', '__module__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'g',
'h'] C.h(3,4)


Traceback (most recent call last):
File "<pyshell#62>", line 1, in -toplevel-
C.h(3,4)
TypeError: unbound method h() must be called with C instance as first argument
(got int instance instead)
Jul 18 '05 #1
1 1712
"Fernando Rodriguez" <fr*@easyjob.net> wrote in message
news:7k********************************@4ax.com...
Hi,

This sort of code works for staticmethods, but fails with instance methods. Why does it fail? O:-)

class C (object): def g(x,y):
print 'static g', x, y
g = staticmethod(g)
def h(self, x,y): return x+y
C.h = h
dir(C) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
'__hash__', '__init__', '__module__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'g',
'h'] C.h(3,4)
Traceback (most recent call last):
File "<pyshell#62>", line 1, in -toplevel-
C.h(3,4)
TypeError: unbound method h() must be called with C instance as first argument (got int instance instead)

Hi.
It fails because "C.h = h" adds an unbound instance method to C, not a
static method.
To use an unbound instance method, you either need to call it on an instance
of C
(e.g., c.h(x,y)) or pass an instance of C as the first parameter (e.g.,
C.h(c, x, y)).

For example:
class C: pass .... def f(self, x, y): .... return x + y
.... C.f = f
C.f <unbound method C.f>
c = C()
c.f(2,3) 5 C.f(c, 2,3) 5

If you want to have the same behaviour as a static method, use
staticmethod():
def g(): .... print "hello"
.... C.g = g
C.g() Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: unbound method g() must be called with C instance as first
argument (got nothing instead) C.g = staticmethod(g)
C.g() hello


HTH
Sean
Jul 18 '05 #2

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...
34
by: Adam Hartshorne | last post by:
Hi All, I have the following problem, and I would be extremely grateful if somebody would be kind enough to suggest an efficient solution to it. I create an instance of a Class A, and...
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 .......
3
by: Gabriele *darkbard* Farina | last post by:
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...
4
by: DotNetJunky | last post by:
I have built a control that runs an on-line help system. Depending on the category you selected via dropdownlist, it goes out and gets the child subcategories, and if there are any, adds a new...
20
by: Ash Phillips | last post by:
Hi Everyone, I have this program I wrote in VB6 for family use. It's a DVD Database just for me to keep track of them cause I have so many lol. In VB6, I could add items to the ListView in...
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 =...
1
by: Allen | last post by:
I need a way to add a method to an existing instance, but be as close as possible to normal instance methods. Using 'new' module or such code as 'def addfunc(...): def helper(...) .. setattr(...)'...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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
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,...

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.