如何节省函数的needed_function调用次数?它被many_functions_that_calling_needed_function1等函数调用。我有如下的类模式:
class MyClass
def __init__
...
def my_function
...
@staticmethod
def needed_function
if first_statement:
"""Count number of calling if statement"""
elif second statement:
"""Count number of calling elif statement"""
def many_functions_that_calling_needed_function1
self.needed_function()
def many_functions_that_calling_needed_function2
self.needed_function()
def many_functions_that_calling_needed_function3
self.needed_function()
def many_functions_that_calling_needed_function4
self.needed_function()发布于 2021-02-09 16:16:30
如果你只需要跟踪一个类(一个方法)内的一个函数被调用了多少次,你可以这样做:
class TestClass:
def __init__(self):
self.calls=0
def needed_function(self):
"""if this function gets called, increase the value of self.calls by 1"""
self.calls+=1
# add whatever else you want here
c=TestClass()
print(c.calls) # prints 0 cause needed_function hasn't been called yet
c.needed_function() # needed_function is called here
print(c.calls) # prints 1
c.needed_function() # called again
print(c.calls) # prints 2https://stackoverflow.com/questions/66114753
复制相似问题