Skip to main content
 首页 » 编程设计

Python之赋值前引用的变量

2025年05月04日16mfryf

我的代码是:

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

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

请您参考如下方法:

由于 noOfCl 是一个类变量,您需要在它前面加上类名前缀。

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

此外,Python 不支持调用 print 函数/语句时的就地更新。