使用类变量时,“ global”名称未定义错误 [英] `global` name not defined error when using class variables

查看:104
本文介绍了使用类变量时,“ global”名称未定义错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,我在这里收到全局名称未定义的错误。问题出在 addClient 方法中,在这里我增加了全局变量 joinID 。它抛出一个错误 NameError:未定义全局名 joinID 。我在做什么错?

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)


推荐答案

将变量带到类之外

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

这篇关于使用类变量时,“ global”名称未定义错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆