如何根据函数是否被调用有条件地执行代码?
How do I conditionally execute code based on if a function is called or not?
我该怎么做:
在 python 中,如何执行循环或 if 语句,以便进入循环/if 语句,您需要调用一个函数。
我的意思是这样的:
if function() *is called*:
print('function() is called')
感谢
使用装饰器包装函数,这样每次函数被调用时,您都会得到一个打印,而无需更改原始函数
def is_called(func):
def wrap():
func()
print func, "is called"
return wrap
@is_called
def function():
pass
if function():
pass #do
将打印 'function is called'
你应该使用布尔值来处理:
def function():
function.has_been_called = True
pass
function.has_been_called = False
#Actual Code!:
if function.has_been_called:
print('function()is called')
布尔值现在将存储函数是否已被调用。
我该怎么做: 在 python 中,如何执行循环或 if 语句,以便进入循环/if 语句,您需要调用一个函数。 我的意思是这样的:
if function() *is called*:
print('function() is called')
感谢
使用装饰器包装函数,这样每次函数被调用时,您都会得到一个打印,而无需更改原始函数
def is_called(func):
def wrap():
func()
print func, "is called"
return wrap
@is_called
def function():
pass
if function():
pass #do
将打印 'function is called'
你应该使用布尔值来处理:
def function():
function.has_been_called = True
pass
function.has_been_called = False
#Actual Code!:
if function.has_been_called:
print('function()is called')
布尔值现在将存储函数是否已被调用。