kivy - How to put "if the function has been called this many times" in Python? -


so i'm designing hangman game using python , kivy , want add win/lose option.

one of functions i've defined button_pressed hides button if it's been pressed want function man_is_hung() have says "if button has been pressed 6 times, show "game over"."

would please me?

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

use decorator:

example:

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

demo:

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

in py3.x can use nonlocal achieve same thing using function instead of class:

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 

demo:

>>> _ in range(6):func(1,1) >>> func(1, 1)     ...     raise typeerror('enough button pressing') typeerror: enough button pressing 

Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -