繁体   English   中英

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

[英]How can I pass a function to a class's method in 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)

这是工作代码

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

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

watcher = Alerter()
watcher.watch(service_check)

正如@ Tomothy32提到的,有2个更改。

  1. 需要在def watch(self,f)中添加Self。 这是因为,只要对象调用其方法,该对象本身就会作为第一个参数传递。
  2. 第二,我们应该传递函数指针watcher.watch(service_check)而不是函数调用watcher.watch(service_check())。

watch()函数缺少self的参数,因此上述程序会引发异常。 另外,您应该只传递函数的名称以在watcher.watch(service_check)中传递其地址,而不是通过service_check()进行调用。 程序应按@ arunraja-a的建议对这些更改正常运行。

暂无
暂无

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

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