如果在類 CLASS. 中執行某個特定函數,我想計算執行了多少次。在類 counting_function_execution 中,通過在類中執行全局變數並每次執行函數來增加它:class CLASS:
global counting_function_execution
counting_function_execution = 0
def __init__(self,name):
self.name = name
def FUNCTION(self):
print("Hi" + self.name)
print("This function was already excecuted", counting_function_execution," number of times.")
counting_function_execution += 1
但是,當我完成它的時候:test = CLASS("Fred")
test.FUNCTION()
test.FUNCTION()
我知道了---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
in ()
1 test = CLASS("Fred")
----> 2 test.say_hi()
in say_hi(self)
8 def say_hi(self):
9 print("Hi" + self.name)
---> 10 print("This function was already excecuted", counting_function_execution," number of times.")
11 counting_function_execution += 1
12
UnboundLocalError: local variable 'counting_function_execution' referenced before assignment