简体   繁体   English

Python:将接受参数的函数传递给类方法?

[英]Python: Pass a function that accepts arguments to a class method?

Dear all please consider this is my first week in Python, I am trying to create a threaded function that created timers which call a specific function. 亲爱的所有人,请考虑这是我使用Python的第一周,我正在尝试创建一个线程化函数,该函数创建了调用特定函数的计时器。 Here is my code: 这是我的代码:

import threading
class TimerClass(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.event = threading.Event()
        self.event.set = False
    def run(self, timer_wait, my_fun(print_text)):
        while True:
            my_fun(print_text)
            self.event.wait(timer_wait)

    def stop(self):
        self.event.set = True




def my_fun(text_to_print):
    print(text_to_print)


tmr = TimerClass()
tmr.run(3, my_fun('hello world'))

The result of this code is 该代码的结果是

def run(self, timer_wait, my_fun(print_text))
                                  ^
SyntaxError: invalid syntax

How can I correct this code? 如何更正此代码? Many thanks! 非常感谢!

Just pass the argument separately: 只需单独传递参数:

def run(self, timer_wait, my_fun, print_text): 
    while check_session_live(session):
        my_fun(print_text)
        self.event.wait(timer_wait)

and call it: 并称之为:

mr.run(3, my_fun, 'hello world')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM