python - 查看函数是否被调用

标签 python python-3.x

我正在用 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/

相关文章:

python - 两个日期之间的天数?

python - 通过蓝牙串行端口配置文件(SPP)将数据从一台Mac发送到另一台Mac

python-3.x - Beautifulsoup 解析千页

python - Pytorch:如何通过python字典中的张量(键)访问张量(值)

python - 使用 'raise from' 语法时链式异常的完整回溯

python - for 循环后无法追加 numpy 数组吗?

python - 验证证书的指纹

python - 选择一列来制作直方图

python - Windows 服务器上的 s3cmd 工具,具有进度支持

python - 套接字未连接Python