如何通过函数实例调用python中的成员函数?;
假设我们有以下代码:如何通过函数实例调用python中的成员函数?;,python,Python,假设我们有以下代码: class T(object): def m1(self, a): ... f=T.m1 如何在T的实例上调用f x=T() x.f(..)? f(x, ..)? 希望这能解释它 class T(object): def m1(self, a): return a f=T().m1 #must initialize the class using '()' before calling a method of that class f
class T(object):
def m1(self, a):
...
f=T.m1
如何在T的实例上调用f
x=T()
x.f(..)?
f(x, ..)?
希望这能解释它
class T(object):
def m1(self, a):
return a
f=T().m1 #must initialize the class using '()' before calling a method of that class
f(1)
f = T()
f.m1(1)
f = T().m1(1)
f = T
f().m1(1)
f = T.m1
f(T(), 1) #can call the method without first initializing the class because we pass a reference of the methods class
f = T.m1
f2 = T()
f(f2, 1)
成员函数与任何其他函数一样,只是它将
self
作为第一个参数,并且有一种自动传递该参数的机制
因此,简单的答案是,用这种方式:
class T(object):
def m1(self, a):
pass
f=T.m1
x = T()
f(x, 1234)
非绑定方法
这是因为您使用的是T.m1,这是一种“未绑定方法”。这里Unbound意味着它的self
参数没有绑定到实例
>>> T.m1
<unbound method T.m1>
您可以引用绑定方法并使用它,而无需显式传递self
:
f2 = x.m1
f2(1234)
使用部分绑定
您还可以使用以下代码自己执行等效的“绑定”self
:
import functools
unbound_f = T.m1
bound_f = functools.partial(unbound_f, x)
bound_f(1234)
您也可以使用
@staticmethod
decorator@RafazZ如果您使用@staticmethod
,您将有不同的行为。该函数将没有self
参数。在这里,m1
在我写的三个案例中,每一个都会收到一个self
。如果m1
中未使用self
,则是-@staticmethod
将是首选解决方案。
import functools
unbound_f = T.m1
bound_f = functools.partial(unbound_f, x)
bound_f(1234)