Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

python - is there a way to track the number of times a function is called?

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()

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...