【问题标题】:How to put "if the function has been called this many times" in Python?如何在 Python 中输入“如果函数已被多次调用”?
【发布时间】:2013-09-25 03:28:04
【问题描述】:

所以我正在使用 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)

【问题讨论】:

  • 您需要将状态保存在对象成员或global

标签: python kivy


【解决方案1】:

使用decorator

示例:

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

【讨论】:

  • 这是一个非常新颖的想法。不知道好不好。
  • 这可能是我使用装饰器的第一件事(函数簿记)。它使您的代码更简洁,并且很容易删除/更改。
【解决方案2】:

您可以像这样将按钮存储为一个类:

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 打败了我。他的解决方案是我上面所说的更通用的解决方案。

【讨论】:

    【解决方案3】:

    这是一种在不涉及全局变量或类的函数中使用静态变量的方法:

    def foobar():
        foobar.counter = getattr(foobar, 'counter', 0)
        foobar.counter += 1
        return foobar.counter
    
    for i in range(5):
        print foobar()
    

    【讨论】:

      【解决方案4】:

      嗯嗯

      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
      

      这将是一种方法......我有点惊讶你已经走到了这一步,却不知道如何保存简单的状态。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-27
        • 2013-05-18
        • 1970-01-01
        • 2020-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多