函数作为python中的参数

时间:2015-03-10 09:46:52

标签: python function arguments

我需要在另一个函数中传递一些函数作为参数。所以,我想每秒向class属性添加当前时间,例如

import time
class Measurement():
    values = []
    def add_value(self, value):
        print "added value"
        self.values.append(value)


def smart_delay(input_function,args):
    start_time = time.time()
    while 5 > (time.time() -  start_time):
        print "Calling function"
        input_function(args)
        time.sleep(1)

measurement = Measurement()

smart_delay(measurement.add_value,time.time())

好的,但是在检查了measurement.values的内容后,我明白了 [1425980407.173, 1425980407.173, 1425980407.173, 1425980407.173] - 所以价值是一样的!!! 发生了什么?以及如何获得正确的价值观?

更新

实际上,这个问题是关于允许调用某个函数的方法,作为参数传递给另一个函数。你怎么看待这个:

import time

class Measurement():
    values = []
    def add_value(self, value):
        print "added value"
        self.values.append(value)


def smart_delay(input_function):
    start_time = time.time()
    while 5 > (time.time() -  start_time):
        print "Calling function"
        input_function()
        time.sleep(1)

measurement = Measurement()

smart_delay(lambda: measurement.add_value(time.time()))

1 个答案:

答案 0 :(得分:3)

在致电time.time()之前,您的smart_delay(...)来电已经执行,因此smart_delay(measurement.addvalue, time.time())将首先从time.time()获取返回值并将其转发至smart_delay }。

您需要传递time.time函数本身,并在smart_delay方法中调用它,而不是传递其返回值:

import time
class Measurement():
    values = []
    def add_value(self, value):
        print "added value"
        self.values.append(value)


def smart_delay(output_f, input_f):
    start_time = time.time()
    while 5 > (time.time() -  start_time):
        print "Calling function"
        output_f(input_f())
        time.sleep(1)

measurement = Measurement()

smart_delay(measurement.add_value, time.time)

请注意,这不是做你正在做的事情的最佳方式,但它有效。


我是这样做的:

import time

# Why do you need a measurement class which only acts as a list anyways?
my_measurements = []

def repeat(duration, function, args=(), kwargs={}, interval=1):
    """Repeat a function call for the given duration."""
    start_time = time.time()
    while duration > time.time() - start_time:
        function(*args, **kwargs)
        time.sleep(interval)

def add_time_measurement(measurements):
    measurements.append(time.time())

repeat(5, add_time_measurement, (my_measurements,))

如果你想要一些打印件,你可以在add_time_measurement功能中添加它们。