基于 this question ,我知道如何计算函数 FUNCTION
在类 CLASS
的实例中执行了多少次。现在,我有另一个问题:我如何计算第二个函数 FUNCTION2
在第一个函数 之后执行了多少次(对于类
被执行了?CLASS
的一个实例) FUNCTION
这是我如何尝试的一个小例子:
class CLASS:
# Initializing counting for first function
counting_function_execution = 0
def __init__(self,name):
self.name = name
def FUNCTION1(self):
# Initializing counting for second function
counting_excution_after_FUNCTION = 0
self.counting_function_execution += 1
print("FUNCTION 1 was excecuted ", self.counting_function_execution, " time.")
def FUNCTION2(self):
counting_excution_after_FUNCTION += 1
print("FUNCTION 2 was excecuted ", self.counting_excution_after_FUNCTION, " time after FUNCTION.")
...但是我得到了:
test = CLASS("Fred")
test.FUNCTION1()
test.FUNCTION2()
test.FUNCTION2()
输出:
FUNCTION 1 was excecuted 1 time.
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-148-d67aeefa671e> in <module>()
1 test = CLASS("Fred")
2 test.FUNCTION1()
----> 3 test.FUNCTION2()
4 test.FUNCTION2()
<ipython-input-147-6a6d7adb1af9> in FUNCTION2(self)
15
16 def FUNCTION2(self):
---> 17 counting_excution_after_FUNCTION += 1
18 print("FUNCTION 2 was excecuted ", self.counting_excution_after_FUNCTION, " time after FUNCTION.")
UnboundLocalError: local variable 'counting_excution_after_FUNCTION' referenced before assignment
最佳答案
如果您跟踪 FUNCTION1
被调用的次数,您可以在 FUNCTION2
中测试它并确保它在开始计数之前大于零 FUNCTION2
:
class CLASS:
def __init__(self,name):
self.name = name
# initialize instance counters -- each instance gets its own counts
self.counting_function_execution_1 = 0
self.counting_function_execution_2 = 0
def FUNCTION1(self):
self.counting_function_execution_1 += 1
print("FUNCTION 1 was excecuted ", self.counting_function_execution_1, " number of times.")
def FUNCTION2(self):
if self.counting_function_execution_1: # don't count unless function1 has run
self.counting_function_execution_2 += 1
print("FUNCTION 2 was excecuted ", self.counting_function_execution_2, " number of times after FUNCTION.")
c = CLASS('the dude')
c.FUNCTION2() #0
c.FUNCTION2() #0
c.FUNCTION1()
c.FUNCTION2() #1
c.FUNCTION2() #2
关于python - 统计一个类的实例在执行完另一个函数后执行了多少次函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55736676/