且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-09 23:22:16

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

# 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") 

I know that in Python that if, say you want to pass two parameters to a function, one an object, and another that specifies the instance method that must be called on the object, the user can easily pass the object itself, along with the name of the method (as a string) then use the getattr function on the object and the string to call the method on the object.

Now, I want to know if there is a way (as in C++, for those who know) where you pass the object, as well as the actual method (or rather a reference to the method, but not the method name as a string). An example:

def func(obj, method):
    obj.method();

I have tried passing it as follows:

func(obj, obj.method)

or as

func(obj, classname.method)

but neither works (the second one I know was a bit of a long shot, but I tried it anyway)

I know that you can also just define a function that just accepts the method, then call it as

func2(obj.method)

but I am specifically asking about instances where you want a reference to the object itself, as well as a reference to a desired class instance (not static) method to be called on the object.

EDIT:

For those that are interested, I found quite an elegant way 'inspired' by the accepted answer below. I simply defined func as

def func(obj, method):
     #more code here
     method(obj, parameter);     #call method on object obj

and called it as

func(obj_ref, obj_class.method);

where obj_class is the actual class that obj_ref is an instance of.

A method is just a function with the first parameter bound to an instance. As such you can do things like.

# 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")