【问题标题】:Using a class method as an argument to a function使用类方法作为函数的参数
【发布时间】:2021-11-21 07:26:46
【问题描述】:

我想将类方法作为参数传递给将方法应用于实例的函数。我写了一个关于我的问题的简化示例,但它不起作用。有没有办法在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'
        

【问题讨论】:

    标签: python function oop functional-programming


    【解决方案1】:

    代替

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

    你应该这样做:

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

    记住方法被定义为def combine(self) - 通过调用func(instance)instance 就变成了self

    Try it online!

    【讨论】:

    • 哇,我也不知道这种行为!这就是我打算写的解决方案。感谢您的许可。:)
    【解决方案2】:

    你可以使用getattr():

    def apply_func(instance, func):
        fn = getattr(instance, func)
        return fn()
    
    
    print(apply_func(A(), 'combine'))
    

    输出:

    6
    

    【讨论】:

    • 谢谢!我不知道getattr,它有效!
    • 实际上并不是“传递一个类方法”,只是它的名字。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    • 2020-02-09
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    相关资源
    最近更新 更多