[英]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)我在 af() 行收到以下错误:TypeError: f() 恰好采用 1 个参数(给定 0)
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.问题似乎是,当将 f 添加到实例 a 时,它被视为存储在 a 内部的 function,而不是实际成员 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?
如果我将 af() 更改为 af(a),那么我得到了预期的效果,但是有没有办法让 python 以这种方式解释原始示例? In other words, is there a way to add a member function to an instance of a class at runtime?
换句话说,有没有办法在运行时将成员 function 添加到 class 的实例?
Thanks谢谢
For Python 2.X you can use:对于 Python 2.X,您可以使用:
import types
class C:
pass
def f(self):
print self
a = C()
a.f = types.MethodType(f,a)
a.f()
For Python 3.X:对于 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...您应该将
f
放在 class 中,而不是在实例中...
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. 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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.