我想计算我在类 CLASS 中执行特定函数 我试图通过在类 FUNCTION 的次数。 中定义一个全局变量来做到这一点code>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)
<ipython-input-104-dc8f3ae96700> in <module>()
1 test = CLASS("Fred")
----> 2 test.say_hi()
<ipython-input-100-d0166079c633> 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
请您参考如下方法:
问题是,在函数 CLASS.FUNCTION 中,您没有引用类变量 counting_function_execution,而是另一个同名的局部变量。< br/> 这就是错误“在赋值前被引用”的原因,因为您在初始化之前引用了该局部变量。
要引用正确的变量,您可以使用self.counting_function_execution(实例的变量),或CLASS.counting_function_execution(类的静态变量)
