【发布时间】:2018-01-14 01:55:07
【问题描述】:
我的问题是如何计算“函数内的方法调用”?
我的意思是在下面的示例中,替换活动在函数内发生了两次。但我能做的就是运行一个计数器来检查:函数执行了多少次。
def replace (newString,i=[0]):
oldString = 'This is word. This is another sample word.'
newString = oldString.replace('word', 'WORD')
print(newString)
i[0]+=1
return i[0]
如何统计函数内方法调用的执行次数,并在python中抛出一个输出来跟踪它?
Output:
This is WORD. This is another sample WORD.
1
Expected output:
This is WORD. This is another sample WORD.
2
【问题讨论】:
-
这没有什么意义,因为
oldString.replace()方法只发生一次。那为什么会是 2? -
我同意,但是如何跟踪方法调用?原因方法调用替换了两次。
-
您似乎只是在寻找替换的元素数量,即
'word'在oldString中出现的次数 -
您可以查看profiling tools python 优惠。
-
它替换了两次,但只调用了一次。