简体   繁体   中英

Dynamically add member function to an instance of a class in Python

When I do the following:

class C:
 pass

def f( self ):
 print self

a = C()

a.f = f

a.f()

I get the following error at the line af(): TypeError: f() takes exactly 1 argument (0 given)

The problem appears to be that when f is added to the instance, a, it is treated like a function that is stored inside of a, rather than an actual member function. If I change af() to af(a), then I get the intended effect, but is there a way to make python interpret the original example this way? In other words, is there a way to add a member function to an instance of a class at runtime?

Thanks

For Python 2.X you can use:

import types
class C:
    pass

def f(self):
    print self

a = C()
a.f = types.MethodType(f,a)
a.f()

For Python 3.X:

import types
class C(object):
    pass

def f(self):
    print(self)

a = C()
a.f = types.MethodType(f,a)
a.f()

You should put f in the class, not in the instance...

 class C:
     pass

 def f(self):
    print(self)

 a = C()
 C.f = f
 a.f()

For the interpreter myObject.foo() is the same as myClass.foo(myObject) when the object doesn't hold anything named foo , but a function placed inside a object is just a function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM