Call function twice or more in a loop

2019-02-20 00:20发布

问题:

I use the code below with lambda to call function once in a loop, it works but now I am trying to call the function for specific times like 3 times in a loop, I looked for it and found some solutions but they call function for specific times if there is no loop, when I try it in a loop, nothing changes. Is there a efficient way to do this?

This one works in a loop and print only once. I want something like that to do it for 3 times.

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

once()

This code below doesn't change anything and it keeps on printing forever if it is in a loop, if not it works.

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

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

repeat_fun(3, do)

Also adding counter outside the loop helps but I think there should be a better solution for it.

回答1:

You should work with a decorator, that makes it clear, what you intend to do:

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


回答2:

Another approach is to use function instead of class:

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"