Python-在类实例中调用多个外部函数
我有一个脚本,可以监视文件中的更改,如果发生更改,应该会触发一些操作。这些操作来自于类外定义的两个函数。在类中,我定义了代码的一部分来查找文件中的更改。我不知道如何在类参数中传递两个函数。以下是我脚本的简化部分:Python-在类实例中调用多个外部函数,python,Python,我有一个脚本,可以监视文件中的更改,如果发生更改,应该会触发一些操作。这些操作来自于类外定义的两个函数。在类中,我定义了代码的一部分来查找文件中的更改。我不知道如何在类参数中传递两个函数。以下是我脚本的简化部分: import time, os watch_file = 'my_file.txt' def first_action(): print('First action called') def second_action(): print('Second actio
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())
像上面那样做会调用第一个动作()
和第二个动作()
,但不会在类内部调用。我知道这一点,因为我没有看到印刷的“呼吁第一次行动”或“呼吁第二次行动”
我能够使用以下代码正确触发第一个操作:
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)
你应该没事。打字错误。你的意思是
watcher=watcher(监视文件、第一个动作、第二个动作)
。请注意,我没有调用functions。您希望传递函数本身,而不是调用它们的返回值<代码>观察者(观察文件,第一个动作,第二个动作)。我已经试过了,只得到了“第一个动作”加上一些错误(见德哈姆回答中的注释)。我已经试过了,只得到了“第一个动作”加上一些错误:文件更改调用第一个动作未处理错误:文件更改调用第一个动作未处理错误: