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