繁体   English   中英

如何在Python中放入“如果函数已被多次调用”?

[英]How to put “if the function has been called this many times” in Python?

所以我正在设计一个使用Python和Kivy的子手游戏,我想添加一个胜利/失败选项。

我定义的函数之一是Button_pressed,如果按下了按钮,它将隐藏按钮,但是我希望函数man_is_hung()的内容为“如果按下按钮6次,则显示”游戏结束”。

有人可以帮我吗?

 def button_pressed(button):
        for (letter, label) in CurrentWord:
            if (letter.upper() == button.text): label.text=letter 
        button.text=" " # hide the letter to indicate it's been tried

def man_is_hung():
    if button_pressed(button)

使用装饰器

例:

class count_calls(object):
    def __init__(self, func):
        self.count = 0
        self.func = func
    def __call__(self, *args, **kwargs):
        # if self.count == 6 : do something
        self.count += 1
        return self.func(*args, **kwargs)

@count_calls
def func(x, y):
    return x + y

演示:

>>> for _ in range(4): func(0, 0)
>>> func.count
4
>>> func(0, 0)
0
>>> func.count
5

在py3.x你可以使用nonlocal使用功能,而不是一个类来实现同样的事情:

def count_calls(func):
    count = 0
    def wrapper(*args, **kwargs):
        nonlocal count
        if count == 6:
            raise TypeError('Enough button pressing')
        count += 1
        return func(*args, **kwargs)
    return wrapper

@count_calls
def func(x, y):
    return x + y

演示:

>>> for _ in range(6):func(1,1)
>>> func(1, 1)
    ...
    raise TypeError('Enough button pressing')
TypeError: Enough button pressing

这是在不涉及全局变量或类的函数中具有静态变量的方法:

def foobar():
    foobar.counter = getattr(foobar, 'counter', 0)
    foobar.counter += 1
    return foobar.counter

for i in range(5):
    print foobar()

您可以将按钮存储为如下所示的类:

class button_pressed(Object):
    def __init__(self):
        self.num_calls = 0

    def __call__(self, button):
        self.num_calls += 1
        if self.num_calls > 6:
            print "Game over."
            return None
        else:
           # Your regular function stuff goes here.

这基本上是一个手动装饰器,尽管对于您尝试执行的操作可能有点复杂,但这是对函数进行簿记的一种简便方法。

的确,执行此操作的正确方法是使用装饰器,该装饰器接受您希望函数能够被调用的次数的参数,然后自动应用上述模式。

编辑:啊! hcwhsa击败了我。 他的解决方案是我上面所说的更通用的解决方案。

num_presses = 0
def button_pressed(button):
    global num_presses
    num_presses += 1
    if num_presses > X:
         print "YOU LOSE SUCKA!!!"
    for (letter, label) in CurrentWord:
        if (letter.upper() == button.text): label.text=letter 
    button.text=" " # hide the letter to indicate it's been tried

我会感到惊讶的是,您在不知道如何保存简单状态的情况下走了这么远。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM