简体   繁体   English

Python-分配前引用的变量

[英]Python - variable referenced before assignment

The code I have is: 我的代码是:

class New(Server):
    noOfCl = 0        

    def onConnect(self, socket):
        print "Client connected"
        print (noOfCl+=1)

I am receiving the following error: UnboundLocalError: local variable 'noOfCl' referenced before assignment. 我收到以下错误: UnboundLocalError: local variable 'noOfCl' referenced before assignment. From what I understand, I'm declaring noOfCl before I am referencing it. 据我了解,我在引用noOfCl之前先声明了它。 Anyone have any ideas as to what I'm doing wrong? 有人对我在做什么错有任何想法吗? Thanks 谢谢

As noOfCl is a Class Variable you need to prefix the Class Name before it. 由于noOfCl是类变量,因此需要在类名之前添加前缀。

class New(Server):
    noOfCl = 0        

    def onConnect(self, socket):
        print "Client connected"
        New.noOfCl+=1
        print(New.noOfCl)

Also your in-place update when calling the print function/statement is not supported in Python. 此外,Python不支持调用print函数/语句时的就地更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM