如何在python中将函数传递给类的方法?

2024-06-08 16:39:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个东西,您可以将服务检查代码传递给它,并在它返回false时发出警报—在python中,如何将代码传递给某个东西的实例?你知道吗

#!/usr/bin/env python

def service_check():
    print('service is up')

class Alerter():
    def watch(f):
        f()

watcher = Alerter()
watcher.watch(service_check())

退货:

service is up
Traceback (most recent call last):
  File "./service_alert", line 12, in <module>
    watcher.watch(service_check())
TypeError: watch() takes exactly 1 argument (2 given)

Tags: 实例代码envfalsebinisusrdef
2条回答

watch()函数缺少self的一个参数,因此上述程序引发异常。另外,您应该只传递函数的名称来传递它的地址观察者。观察(服务检查)而不是通过服务检查()打电话。 按照@arunraja-a的建议,程序应该可以很好地处理这些更改

这是工作代码

def service_check():
print('service is up')

class Alerter():
  def watch(self,f):
    f()

watcher = Alerter()
watcher.watch(service_check)

正如@Tomothy32提到的,有两个变化。你知道吗

  1. 需要在def watch(Self,f)中添加Self。这是因为,每当一个对象调用它的方法时,对象本身作为第一个参数被传递。你知道吗
  2. 第二个我们应该传递函数指针观察者。观察(服务检查)而不是函数调用观察者。观察(服务检查()。你知道吗

相关问题 更多 >