在一个循环中调用两次或多次函数 [英] Call function twice or more in a loop
问题描述
我用下面的代码用 lambda
在一个循环中调用一次函数,它可以工作,但现在我试图在特定的时间调用函数,比如3次循环,我寻找它,并找到了一些解决方案,但他们调用功能的特定时间,如果没有循环,当我在循环尝试它,没有任何变化。有没有一种有效的方法来做到这一点?
这一个工作循环,只打印一次。
def once():
printDo function once
once.func_code =(lambda:None).func_code
once()
以下代码不会改变任何内容,如果它处于循环中,它会一直保持打印状态,如果不行的话。
def repeat_fun(times,f):
在范围内(时间):f()
def do():
print' 3次'
repeat_fun(3,do)
外循环有帮助,但我认为应该有一个更好的解决方案。
你应该使用一个装饰器,它清楚,你打算做什么:
$ p $ class call_three_times(object):
def __init __(self,func) :
self.func = func
self.count = 0
def __call __(self,* args,** kw):
self.c ount + = 1
if self.count< = 3:
返回self.func(* args,** kw)
@call_three_times
def func ):
print只调用三次
func()#打印仅调用三次
func()#打印只调用三次
func()#打印仅调用三次
func()#不做任何事
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.
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
这篇关于在一个循环中调用两次或多次函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!