有没有办法跟踪函数被调用的次数? [英] is there a way to track the number of times a function is called?

查看:40
本文介绍了有没有办法跟踪函数被调用的次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在尝试创建一个函数来跟踪方法被调用的次数.例如:

So i'm trying to make a function that keeps track how many times a method is called. for example:

a = [1,2,3,4]
a.pop()

我想知道到目前为止 a.pop() 被调用了多少次,所以对于这个例子,我会得到 1.有没有办法做到这一点?

i want to know how many times a.pop() was called so far so for this example, i would get 1. Is there a way to do this?

推荐答案

这不适用于内置函数,但一个有趣的方法是:

This doesn't work for builtin functions, but an interesting approach would be:

def myfunction():
    myfunction.counter += 1
myfunction.counter = 0

您给函数一个属性,所以每次调用该属性都会更新.不需要全局变量.

You're giving the function an attribute, so every call that attribute is updated. No global variables needed.

内置是只读的.它们不能被修改.

Built-ins are read-only. They cannot be modified.

这篇关于有没有办法跟踪函数被调用的次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆