首页 > 解决方案 > 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必须使用吗?

标签: python

解决方案


您在 init 中做对了,但不是在“Watcher”的调用中。要传递函数本身,而不是返回值,您必须删除大括号。

watcher = Watcher(watch_file, first_action, second_action)

你应该没事。


推荐阅读