如何使函数仅在第一次调用时打印一个值?

时间:2018-03-17 02:10:09

标签: python python-3.x function printing stateful

如何让这个函数在第二次调用时不打印值c?我希望这能用于我的Hangman游戏。

像这样:

def myFunction(first,second,third):
   if first == True:
      # Do this
   elif second == True:
      c = third * 3

      print(c) # I do not want this to print on the second time it run
      return c

   else:
      print("Error")

1 个答案:

答案 0 :(得分:2)

装饰器可以通过使它们成为有状态来以这种方式改变函数的行为。在这里,我们可以注入一个dict参数,其中包含函数可以在其生命周期内更新和重用的某些状态。

def inject_state(state):

    def wrapper(f):

        def inner_wrapper(*args, **kwargs):
            return f(state, *args, **kwargs)

        return inner_wrapper

    return wrapper


@inject_state({'print': True})
def myFunction(state, first, second, third):
   if first == True:
       pass # Do this
   elif second == True:
      c = third * 3

      # We print provided 'print' is True in our state
      if state['print']:
        print(c)

        # Once we printed, we do not want to print again
        state['print'] = False

      return c
   else:
      print("Error")

在这里你看到第二个电话确实没有打印任何东西。

myFunction(False, True, 1) # 3
# prints: 3

myFunction(False, True, 1) # 3
# prints nothing