【问题标题】:How to make a function print a value only on its first call?如何使函数仅在第一次调用时打印值?
【发布时间】:2018-08-26 04:14:13
【问题描述】:

如何让这个函数在第二次调用时不打印值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")

【问题讨论】:

  • IDLE 仅当您在交互模式下运行代码时才会显示它。直接运行源码即可。
  • 源代码是什么意思?
  • 不打印某些东西可以通过不调用 print() 来实现。
  • @PaulCornelius 但我想说只在第一次打印

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


【解决方案1】:

装饰器可用于通过使函数有状态来改变函数的行为。在这里,我们可以注入一个 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

【讨论】:

  • 哇!此代码确实有效,但大小确实很大。但这已经足够了。 @OliverMelancon 谢谢!
  • 这真的只是因为我为了可读性而使内容变得稀疏。我添加的只是 9 行代码和一个简单的示例。
  • @Andrew 顺便说一下,当您在 StackOverflow 上遇到有用的答案时,请不要犹豫,点赞并接受它们,以便其他用户更容易找到它们。我看到你过去没有这样做过。它提高了网站搜索质量,并为您带来了良好的声誉。
  • @Oliver 我的声誉
猜你喜欢
  • 1970-01-01
  • 2020-01-29
  • 1970-01-01
  • 1970-01-01
  • 2019-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多