Python 条件测试/回调机制

Python 条件测试/回调机制,python,callback,conditional-statements,Python,Callback,Conditional Statements,我需要一个简单的类或函数,它接受一个测试(返回True或False的可调用对象)和一个在测试为True时调用的函数,可能在另一个线程中完成整个任务。大概是这样的: nums = [] t = TestClass(test=(lambda: len(nums) > 5), func=(lambda: sys.stdout.write('condition met')) for n in range(10): nums.append(n) time

我需要一个简单的类或函数,它接受一个测试(返回
True
False
的可调用对象)和一个在测试为
True
时调用的函数,可能在另一个线程中完成整个任务。大概是这样的:

nums = []
t = TestClass(test=(lambda: len(nums) > 5),
              func=(lambda: sys.stdout.write('condition met'))

for n in range(10):
    nums.append(n)
    time.sleep(1) 

#after 6 loops, the message gets printed on screen.

感谢您的帮助。(请不要太复杂,因为我还是初学者)

不完全确定您的要求,但我认为这应该有助于您开始学习

def test_something(condition, action, *args, **kwargs):
  if condition():
    action(*args, **kwargs)

def print_success():
  print 'Success'

def test_one():
  return True

test_something(test_one, print_success)

不完全确定你在问什么,但我认为这应该有助于你开始

def test_something(condition, action, *args, **kwargs):
  if condition():
    action(*args, **kwargs)

def print_success():
  print 'Success'

def test_one():
  return True

test_something(test_one, print_success)

您的想法是正确的,您可能需要一个单独的线程来检查后台的条件。在这个单独的线程中,您还必须决定检查的频率(有其他方法可以做到这一点,但这种方法需要对所显示的代码进行最少的更改)

我的答案只是使用了一个函数,但如果您愿意,您可以轻松地使用一个类:

from threading import Thread
import time
import sys    

def myfn(test, callback):

    while not test():  # check if the first function passed in evaluates to True
        time.sleep(.001)  # we need to wait to give the other thread time to run.
    callback() # test() is True, so call callback.

nums = []

t = Thread(target=myfn, args=(lambda: len(nums) > 5, 
           lambda: sys.stdout.write('condition met')))
t.start() # start the thread to monitor for nums length changing

for n in range(10):
    nums.append(n)
    print nums  # just to show you the progress
    time.sleep(1) 

您的想法是正确的,您可能需要一个单独的线程来检查后台的条件。在这个单独的线程中,您还必须决定检查的频率(有其他方法可以做到这一点,但这种方法需要对所显示的代码进行最少的更改)

我的答案只是使用了一个函数,但如果您愿意,您可以轻松地使用一个类:

from threading import Thread
import time
import sys    

def myfn(test, callback):

    while not test():  # check if the first function passed in evaluates to True
        time.sleep(.001)  # we need to wait to give the other thread time to run.
    callback() # test() is True, so call callback.

nums = []

t = Thread(target=myfn, args=(lambda: len(nums) > 5, 
           lambda: sys.stdout.write('condition met')))
t.start() # start the thread to monitor for nums length changing

for n in range(10):
    nums.append(n)
    print nums  # just to show you the progress
    time.sleep(1) 

如果我理解正确,您希望TestClass实例在其测试条件变为true时自动检测?也就是说,你不想做任何事情让它再次检查?那很难。我能想到的唯一方法(使用多个线程,就像你提到的)是有竞态条件的,因为不能保证测试线程在第一次测试为真后立即被激活。如果我理解正确,您希望TestClass实例自动检测其测试条件何时变为true?也就是说,你不想做任何事情让它再次检查?那很难。我能想到的唯一方法(使用多个线程,就像你提到的)是有竞争条件的,因为不能保证测试线程会在第一次测试成为真后立即被激活。这实际上是我考虑的方式,但我担心性能。我想这完全取决于考试的频率,因为增加时间的价值。睡眠也会增加比赛条件的机会。这实际上是我的想法,但我担心的是成绩。我想这完全取决于测试的频率,因为增加时间的价值。睡眠也会增加比赛条件的机会。