如何禁用函数调用一段时间

时间:2018-05-22 02:07:06

标签: python

我是Python的新版本,只使用它大约一个月左右,我想在Python 2.7.2上制作文本rpg。因此,对于某些命令,例如挖掘或捕鱼,我希望在使用命令之后有一段时间,他们无法在特定时间段内再次使用该命令。

while True:
command = raw_input("Say something")
if command = "mine":
    print "You found 2 Rocks! etc."

我想这样做只能每1分钟使用一次命令 例。 如果时间尚未结束,则会打印

print "Please wait a moment(%s seconds remaining)" % timeleft

2 个答案:

答案 0 :(得分:1)

首先,你应该使用Python3。但这取决于你。我的回答使用Python3,但您应该能够轻松转换为Python2。

您可以创建一个字典,其中键是命令,值是上次使用该命令的时间戳。例如:

{{1}}

答案 1 :(得分:0)

这个答案使用Python 3.6

您可以使用闭包:在这种情况下,通过使用带有可变默认值的命名参数。存储函数的最后一次,并与再次调用时的当前时间进行比较。如果时差太短,则函数返回而不执行代码。

import time


disable_time = 5


def do_stuff_then_disable_for_a_while(stamp=[time.time()-disable_time]):
    """will disable for disable_time after each successful use"""
    if time.time() - stamp[0] > disable_time:
        stamp[0] = time.time()
        print("doing stuff")

    else:
        print("currently disabled")


if __name__ == '__main__':

    while True:

        do_stuff_then_disable_for_a_while()
        time.sleep(1)

输出:

doing stuff
currently disabled
currently disabled
currently disabled
currently disabled
doing stuff
currently disabled
currently disabled
currently disabled
currently disabled
doing stuff

用作装饰者:

这是一个经常遇到的问题,试图给它一个更通用的解决方案:以下允许修饰一个函数,设置它被禁用的时间:

import time
from functools import wraps


class _Disabled:
    """helper class for a decorator that disables
    a function for some time delay"""

    def __init__(self, disable_duration):
        self.first_call = True
        self.disable_duration = disable_duration
        self.last_called = time.time()

    def __bool__(self):
        """return True if disabled, False otherwise
        Attention: has a side effect with consequences:
        ==>> upon first time called, sets first_called flag to false
        """
        if self.first_call:
            self.first_call = False
            return False

        _disabled = time.time() - self.last_called > self.disable_duration

        if _disabled:
            self.last_called = time.time()
            return False
        return True


def disable_for_a_while_after_called(disable_time=5):
    """Decorator factory that modifies the decorated functions so that
    after execution, they are disabled for some time, before they can run
    again
    """
    def _disable_for_a_while_after_called(f):
        must_not_call_function = _Disabled(disable_time)

        @wraps(f)
        def wrapped(*args):
            if must_not_call_function:
                r = None
            else:
                r = f(*args)
            return r
        return wrapped
    return _disable_for_a_while_after_called

用法示例:

if __name__ == '__main__':

    @disable_for_a_while_after_called()
    def do_stuff():
        return "doing stuff"


    @disable_for_a_while_after_called(disable_time=2)
    def do_other_stuff():
        return "doing other stuff"


    @disable_for_a_while_after_called(disable_time=13)
    def do_infrequent_stuff():
        return "doing infrequent stuff"


    for s in range(100):
        a = do_stuff()
        b = do_other_stuff()
        c = do_infrequent_stuff()
        print(f"{s}: {a if a is not None else ' '*11}, "
              f"{b if b is not None else ' ' * 17}, "
              f"{c if c is not None else ''}")
        time.sleep(1)

输出:

0: doing stuff, doing other stuff, doing infrequent stuff
1:            ,                  , 
2:            , doing other stuff, 
3:            ,                  , 
4:            , doing other stuff, 
5: doing stuff,                  , 
6:            , doing other stuff, 
7:            ,                  , 
8:            , doing other stuff, 
9:            ,                  , 
10: doing stuff, doing other stuff, 
11:            ,                  , 
12:            , doing other stuff, 
13:            ,                  , doing infrequent stuff
14:            , doing other stuff, 
15: doing stuff,                  , 
16:            , doing other stuff, 
17:            ,                  , 
18:            , doing other stuff, 
19:            ,                  , 
20: doing stuff, doing other stuff, 
21:            ,                  , 
22:            , doing other stuff, 
23:            ,                  , 
24:            , doing other stuff, 
25: doing stuff,                  , 
26:            , doing other stuff, doing infrequent stuff
27:            ,                  , 
28:            , doing other stuff, 
29:            ,                  ,