将对象与对象方法一起传递给函数
Pass object along with object method to function
我知道在 Python 中,如果你想将两个参数传递给一个函数,一个是对象,另一个指定必须在对象上调用的实例方法,用户可以轻松传递对象本身,连同方法名称(作为字符串),然后使用对象上的 getattr
函数和字符串来调用对象上的方法。
现在,我想知道是否有一种方法(如在 C++ 中,对于那些知道的人),您可以在其中传递对象以及实际方法(或者更确切地说是对方法的引用,但不是方法名称作为字符串)。一个例子:
def func(obj, method):
obj.method();
我试过如下传递:
func(obj, obj.method)
或
func(obj, classname.method)
但都不行(我知道的第二个有点远,但我还是试过了)
我知道你也可以只定义一个只接受方法的函数,然后调用它
func2(obj.method)
但我特别询问您想要引用对象本身的实例,以及对所需 class 实例(非静态)的 引用要在对象上调用的方法。
编辑:
对于那些感兴趣的人,我通过下面接受的答案找到了一种非常优雅的方式 'inspired'。我简单地将 func
定义为
def func(obj, method):
#more code here
method(obj, parameter); #call method on object obj
并将其命名为
func(obj_ref, obj_class.method);
其中 obj_class 是实际的 class,obj_ref 是其实例。
你可以搜索getattr
def apiroute(self, apiname, request):
try:
if callable(getattr(self,apiname)):
return getattr(self,apiname)(request)
else:
return "action is not a method"
except:
return "action is not exists"
方法只是一个函数,其第一个参数绑定到一个实例。因此,您可以做类似的事情。
# normal_call
result = "abc".startswith("a")
# creating a bound method
method = "abc".startswith
result = method("a")
# using the raw function
function = str.startswith
string = "abc"
result = function(string, "a")
我知道在 Python 中,如果你想将两个参数传递给一个函数,一个是对象,另一个指定必须在对象上调用的实例方法,用户可以轻松传递对象本身,连同方法名称(作为字符串),然后使用对象上的 getattr
函数和字符串来调用对象上的方法。
现在,我想知道是否有一种方法(如在 C++ 中,对于那些知道的人),您可以在其中传递对象以及实际方法(或者更确切地说是对方法的引用,但不是方法名称作为字符串)。一个例子:
def func(obj, method):
obj.method();
我试过如下传递:
func(obj, obj.method)
或
func(obj, classname.method)
但都不行(我知道的第二个有点远,但我还是试过了)
我知道你也可以只定义一个只接受方法的函数,然后调用它
func2(obj.method)
但我特别询问您想要引用对象本身的实例,以及对所需 class 实例(非静态)的 引用要在对象上调用的方法。
编辑:
对于那些感兴趣的人,我通过下面接受的答案找到了一种非常优雅的方式 'inspired'。我简单地将 func
定义为
def func(obj, method):
#more code here
method(obj, parameter); #call method on object obj
并将其命名为
func(obj_ref, obj_class.method);
其中 obj_class 是实际的 class,obj_ref 是其实例。
你可以搜索getattr
def apiroute(self, apiname, request):
try:
if callable(getattr(self,apiname)):
return getattr(self,apiname)(request)
else:
return "action is not a method"
except:
return "action is not exists"
方法只是一个函数,其第一个参数绑定到一个实例。因此,您可以做类似的事情。
# normal_call
result = "abc".startswith("a")
# creating a bound method
method = "abc".startswith
result = method("a")
# using the raw function
function = str.startswith
string = "abc"
result = function(string, "a")