`global` name not defined error when using class variables

元气小坏坏 提交于 2019-12-24 11:15:00

问题


For some reason I'm getting a global name is not defined error here. The issue lies in the addClient method where I am incrementing my global variable joinID. It throws me an error NameError: global name 'joinID' is not defined. What am I doing wrong?

class Chatroom:
    clients = []
    joinID = 0

    def __init__(self,name,refNum):
        self.refNum = refNum
        self.name = name

    def addClient(self,clientName):
        global clients
        global joinID
        joinID = joinID+1
        clients.append(clientName, joinID)

    def removeClient(self, clientName, joinID):
        global clients
        clients.remove(clientName, joinID)

回答1:


Take the variables outside the class

joinID=0
clients=[]
class Chatroom:
    def __init__(self,name,refNum):



回答2:


In a method from a class is bether to use a instance attribute or a class atribute. In this case you are using a class atribute.

class Chatroom:
    clients=[]
    joinID=0

    def __init__(self,name,refNum):
        self.refNum=refNum
        self.name=name

    def addClient(self,clientName):
        self.joinID=self.joinID+1
        self.clients.append((clientName,self.joinID))

    def removeClient(self,clientName,joinID):
        self.clients.remove((clientName,joinID))

If you wan´t to use global, you must declare the variable in the global scope:

joinId=0
clients=[]
class Chatroom:

    def __init__(self,name,refNum):
        self.refNum=refNum
        self.name=name

    def addClient(self,clientName):
        global joinID
        global clients
        joinID=joinID+1
        clients.append((clientName,joinID))

    def removeClient(self,clientName,joinID):
        global clients
        clients.remove((clientName,joinID))


来源:https://stackoverflow.com/questions/41881061/global-name-not-defined-error-when-using-class-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!