简体   繁体   English

使用 class 方法作为 function 的参数

[英]Using a class method as an argument to a function

I want to pass an class method as an argument to a function which applies the method to an instance.我想将 class 方法作为参数传递给 function,后者将该方法应用于实例。 I wrote a simplified example of my problem down, which does not work.我写了一个我的问题的简化示例,但它不起作用。 Is there a way to do this in python? python有没有办法做到这一点?

class A:
    def __init__(self):
        self.values = [1,2,3]
        
    def combine(self) -> int:
        return sum(self.values)
    
    def return_zero(self) -> int:
        return 0
    

def apply_func(instance, func):
    return instance.func()


print(apply_func(A(), A.combine))

> AttributeError: 'A' object has no attribute 'func'
        

You could use getattr() :你可以使用getattr()

def apply_func(instance, func):
    fn = getattr(instance, func)
    return fn()


print(apply_func(A(), 'combine'))

Out:出去:

6

Instead of代替

def apply_func(instance, func):
    return instance.func()

you should do:你应该做:

def apply_func(instance, func):
    return func(instance)

Remember the method is defined as def combine(self) - by calling func(instance) , the instance simply becomes that self .请记住,该方法被定义为def combine(self) - 通过调用func(instance)instance简单地变成了那个self

Try it online! 在线试用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM