调用一个函数一次可以通过以下几种方式实现:
called = False
def my_function():
global called
if not called:
called = True
# 执行函数体内的代码
def once(func):
called = False
def wrapper(*args, **kwargs):
nonlocal called
if not called:
called = True
return func(*args, **kwargs)
return wrapper
@once
def my_function():
# 执行函数体内的代码
def once(func):
called = False
def wrapper(*args, **kwargs):
nonlocal called
if not called:
called = True
return func(*args, **kwargs)
return wrapper
@once
def my_function():
# 执行函数体内的代码
以上是几种常见的实现方式,可以根据具体的编程语言和场景选择适合的方式来实现只调用一次的函数。
领取专属 10元无门槛券
手把手带您无忧上云