Python - 赋值前引用的变量

Aks*_*hah 1 python variables

我的代码是:

class New(Server):
    noOfCl = 0        

    def onConnect(self, socket):
        print "Client connected"
        print (noOfCl+=1)
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:UnboundLocalError: local variable 'noOfCl' referenced before assignment.根据我的理解,我在引用它之前声明noOfCl.任何人都对我做错了什么有任何想法?谢谢

Abh*_*jit 6

noOfCl类变量一样,您需要在其前面添加类名称前缀.

class New(Server):
    noOfCl = 0        

    def onConnect(self, socket):
        print "Client connected"
        New.noOfCl+=1
        print(New.noOfCl)
Run Code Online (Sandbox Code Playgroud)

printPython中也不支持在调用函数/语句时进行就地更新.

  • @ San4ez:取决于它的3.x还是2.x. 无论Python的版本如何,这都可以. (3认同)