将对象与对象方法一起传递给函数

Kon*_*app 1 python parameters class object

我知道在Python中,如果你想要将两个参数传递给一个函数,一个是一个对象,另一个指定必须在对象上调用的实例方法,那么用户可以轻松地传递对象本身,以及方法的名称(作为字符串)然后使用getattr对象上的函数和字符串来调用对象上的方法.

现在,我想知道是否有一种方法(如在C++中,对于那些知道的人)传递对象的位置,以及实际方法(或者更确切地说是对方法的引用,但不是方法名称作为字符串).一个例子:

def func(obj, method):
    obj.method();
Run Code Online (Sandbox Code Playgroud)

我试过传递如下:

func(obj, obj.method)
Run Code Online (Sandbox Code Playgroud)

或者作为

func(obj, classname.method)
Run Code Online (Sandbox Code Playgroud)

但是都不起作用(我认识的第二个是一个很长的镜头,但无论如何我试过了)

我知道您也可以定义一个只接受该方法的函数,然后将其称为

func2(obj.method)
Run Code Online (Sandbox Code Playgroud)

但我特别询问您希望引用对象本身的实例,以及对要在对象上调用的所需类实例(非静态)方法的引用.

编辑:

对于那些感兴趣的人,我发现了一个非常优雅的方式,受到下面接受的答案的"启发".我只是定义func

def func(obj, method):
     #more code here
     method(obj, parameter);     #call method on object obj
Run Code Online (Sandbox Code Playgroud)

并称之为

func(obj_ref, obj_class.method);
Run Code Online (Sandbox Code Playgroud)

其中obj_class是obj_ref是其实例的实际类.

Dun*_*nes 6

方法只是第一个参数绑定到实例的函数.因此,你可以做类似的事情.

# 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") 
Run Code Online (Sandbox Code Playgroud)