如何让一个函数只在第一次调用时打印一个值?
How to make a function print a value only on its first call?
如何让这个函数在第二次调用时不打印值 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")
装饰器可用于通过使函数有状态来以这种方式更改函数的行为。在这里,我们可以注入一个 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
如何让这个函数在第二次调用时不打印值 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")
装饰器可用于通过使函数有状态来以这种方式更改函数的行为。在这里,我们可以注入一个 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