[英]Python - call multiple external functions in Class instance
我有一個腳本來監視文件的變化,如果發生它應該觸發一些動作。 這些動作來自 Class 外部定義的兩個函數。 在 Class 中,我定義了部分代碼來查找文件中的更改。 我無法弄清楚如何在 Class arguments 中傳遞兩個函數。 這是我的腳本的簡化部分:
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()
但不在 Class 內部。 我知道是因為我沒有看到打印的“調用第一個動作”或“調用第二個動作”我能夠使用以下代碼正確觸發第一個動作:
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)
出於某種原因,我需要為 function 指定*args
,它在調用時不接受任何參數。 有人可以解釋為什么必須使用*args
嗎?
您在 init 中做對了,但不是在“Watcher”的調用中。 要傳遞 function 本身,而不是它的返回值,您必須刪除大括號。
watcher = Watcher(watch_file, first_action, second_action)
你應該沒事。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.