Bil*_*ljk 16 python python-3.x
我正在用Python编程,我想知道我是否可以测试我的代码中是否调用了函数
def example():
pass
example()
#Pseudocode:
if example.has_been_called:
print("foo bar")
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
agf*_*agf 25
如果函数知道自己的名称是可以的,可以使用函数属性:
def example():
example.has_been_called = True
pass
example.has_been_called = False
example()
#Actual Code!:
if example.has_been_called:
print("foo bar")
Run Code Online (Sandbox Code Playgroud)
您还可以使用装饰器来设置属性:
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")
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13823 次 |
最近记录: |