我正在用 Python 编程,我想知道我是否可以测试我的代码中是否调用了一个函数
def example():
pass
example()
#Pseudocode:
if example.has_been_called:
print("foo bar")
我该怎么做?
最佳答案
如果函数知道自己的名字是可以的,你可以使用一个函数属性:
def example():
example.has_been_called = True
pass
example.has_been_called = False
example()
#Actual Code!:
if example.has_been_called:
print("foo bar")
您还可以使用装饰器来设置属性:
import functools
def trackcalls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
wrapper.has_been_called = True
return func(*args, **kwargs)
wrapper.has_been_called = False
return wrapper
@trackcalls
def example():
pass
example()
#Actual Code!:
if example.has_been_called:
print("foo bar")
关于python - 查看函数是否被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9882280/