[英]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个更改。
watch()函数缺少self的参数,因此上述程序会引发异常。 另外,您应该只传递函数的名称以在watcher.watch(service_check)中传递其地址,而不是通过service_check()进行调用。 程序应按@ arunraja-a的建议对这些更改正常运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.