Call function twice or more in a loop

前端 未结 2 1436
予麋鹿
予麋鹿 2021-01-15 13:55

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

2条回答
  •  别那么骄傲
    2021-01-15 14:20

    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
    

提交回复
热议问题