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

Python 如何使函数仅在第一次调用时打印值?,python,python-3.x,function,printing,stateful,Python,Python 3.x,Function,Printing,Stateful,如何使此函数在第二次调用时不打印值c?我想把这个作为我的刽子手游戏 像这样: 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 els

如何使此函数在第二次调用时不打印值
c
?我想把这个作为我的刽子手游戏

像这样:

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")

修饰符可以通过使函数具有状态来改变函数的行为。在这里,我们可以插入一个
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

只有在交互模式下运行代码时,IDLE才会显示它。直接运行源代码。你说的源代码是什么意思?不打印某些东西可以通过不调用print()来实现。@PaulCornelius但我想说的是只在第一次打印哇!这段代码确实有效,但大小确实很大。但这已经足够好了@奥利弗·兰肯,谢谢!这真的只是因为为了可读性,我把东西做得很稀疏。我只添加了9行代码和一个简单的例子。@Andrew顺便说一句,当你在StackOverflow上遇到有用的答案时,请毫不犹豫地向上投票并接受它们,以便其他用户可以更轻松地找到它们。我看你过去没有这样做过。它提高了网站搜索质量,给了你一些好名声。@Oliver我的名声<15所以是的。