简体   繁体   中英

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. From what I understand, I'm declaring noOfCl before I am referencing it. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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