python - Python - 在类实例中调用多个外部函数
问题描述
我有一个脚本来监视文件的变化,如果发生它应该触发一些动作。这些动作来自定义在 Class 之外的两个函数。在类中,我定义了部分代码来查找文件中的更改。我不知道如何在类参数中传递两个函数。这是我的脚本的简化部分:
import time, os
watch_file = 'my_file.txt'
def first_action():
print('First action called')
def second_action():
print('Second action called')
class Watcher():
def __init__(self, watch_file, first_action=None, second_action=None):
self._cached_stamp = 0
self.filename = watch_file
self.first_action = first_action
self.second_action = second_action
# Look for changes in 'my_file.txt'
def look(self):
stamp = os.stat(self.filename).st_mtime
if stamp != self._cached_stamp:
self._cached_stamp = stamp
# File has changed, so do something...
print('File changed')
if self.first_action is not None:
print('Call first action')
self.first_action(self)
if self.second_action is not None:
print('Call second action')
self.second_action(self)
watcher = Watcher(watch_file, first_action(), second_action())
像上面的调用那样做first_action()
,second_action()
但不是在类里面。我知道是因为我没有看到打印的“调用第一个动作”或“调用第二个动作”我能够使用以下代码正确触发第一个动作:
watch_file = 'my_file.txt'
def first_action():
print('First action called')
def second_action():
print('Second action called')
class Watcher():
def __init__(self, watch_file, first_action=None, *args):
self._cached_stamp = 0
self.filename = watch_file
self.first_action = first_action
self.args = args
# Look for changes in 'my_file.txt'
def look(self):
stamp = os.stat(self.filename).st_mtime
if stamp != self._cached_stamp:
self._cached_stamp = stamp
# File has changed, so do something...
print('File changed')
if self.first_action is not None:
print('Call first action')
self.first_action(*self.args)
watcher = Watcher(watch_file, first_action)
出于某种原因,我*args
什至需要为在调用时不带任何参数的函数指定。有人可以解释为什么*args
必须使用吗?
解决方案
您在 init 中做对了,但不是在“Watcher”的调用中。要传递函数本身,而不是返回值,您必须删除大括号。
watcher = Watcher(watch_file, first_action, second_action)
你应该没事。
推荐阅读
- wav - NAudio 拆分 wav 文件问题。其他所有音频文件声音失真,而其他音频文件清晰
- excel - COUNTIFS,多个条件,仅包括日期范围内的特定值
- c# - 生成许多与float(System.Single)具有相同功能的结构类型
- java - 无法在 Java FX 中修复 GridPane 周围的样式边框
- android - 意外的令牌 - android studio
- javascript - 一键使用两个或多个 URL 用于不同的 ajax
- java - 尝试导入 VMStack 和 CallerSensitive 时,类 DriverManager 出现错误
- node.js - Bot Framework 中的轮播 - 从数据库中不断更新 - 在滚动时?
- dart - 了解 Dart 私人课程
- css - 无法通过 css 选择 [type:radio]