在循环中调用两次或更多次函数

hzl*_*rdo 2 python lambda loops function python-2.7

我使用下面的代码lambda在循环中调用函数一次,它工作但现在我试图在循环中调用函数特定时间,如3次,我找了它并找到了一些解决方案,但他们调用函数特定时间如果没有循环,当我在循环中尝试它时,没有任何变化.有没有一种有效的方法来做到这一点?

这个工作循环并只打印一次.我想要这样的东西做3次.

def once():
    print "Do function once"
    once.func_code = (lambda:None).func_code

once()
Run Code Online (Sandbox Code Playgroud)

下面这段代码不会改变任何东西,如果它在一个循环中,它会一直打印,如果它不起作用.

def repeat_fun(times, f):
    for i in range(times): f()

def do():
    print 'Do function for 3 times'

repeat_fun(3, do)
Run Code Online (Sandbox Code Playgroud)

在循环外添加计数器也有帮助,但我认为应该有更好的解决方案.

Dan*_*iel 6

您应该使用装饰器,使其清楚,您打算做什么:

class call_three_times(object):
    def __init__(self, func):
        self.func = func
        self.count = 0

    def __call__(self, *args, **kw):
        self.count += 1
        if self.count <= 3:
            return self.func(*args, **kw)

@call_three_times
def func():
    print "Called only three times"

func() # prints "Called only three times"
func() # prints "Called only three times"
func() # prints "Called only three times"
func() # does nothing
Run Code Online (Sandbox Code Playgroud)


Vad*_*rda 5

另一种方法是使用函数而不是类:

def call_three_times(func, *args, **kwargs):
    def wrapper(*args, **kwargs):
        wrapper.called += 1
        return func(*args, **kwargs) if wrapper.called <= 3 else None
    wrapper.called = 0
    return wrapper


@call_three_times
def func():
    print "Called only three times"
Run Code Online (Sandbox Code Playgroud)