1

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)
2
  • 1
    Your indentation looks broken. Also, are you aware of the difference between "x" and "self.x"? Commented Jan 26, 2017 at 19:13
  • Quite simply, joinID is not defined. Nowhere is there a joinID variable declared. Commented Jan 26, 2017 at 19:13

2 Answers 2

4

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))
Sign up to request clarification or add additional context in comments.

Comments

1

Take the variables outside the class

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

1 Comment

or use the self. prefix to look up the variables via the instance, or Chatroom. prefix to access them via the class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.