Python类中误用global引用类属性触发NameError,如何解决?
问题描述
我在Python中编写了如下代码,尝试在command类中定义类属性OutF,并在类方法Out中使用global关键字引用该属性:
class command: OutF = str() def Out(outputRange: int, ArgsFormat: list): global OutF ArgsFormat[0] = None; for i in range(outputRange): OutF += " " + ArgsFormat[i] list = ["zero", "one", "two", "three", "thisisjustexampleforwhathappend"] command.Out(list.__len__(), list) print(command.OutF)
运行代码时触发如下错误:
NameError: name 'OutF' is not defined
修复方案
问题核心是误用了global关键字:global用于引用全局作用域的变量,而OutF是command类的类属性,不属于全局作用域,因此报错。以下两种方式可修复:
方式一:通过类名直接访问类属性
直接在方法中使用command.OutF引用类属性,删除无效的global声明:
class command: OutF = str() def Out(outputRange: int, ArgsFormat: list): ArgsFormat[0] = None for i in range(outputRange): command.OutF += " " + ArgsFormat[i] my_list = ["zero", "one", "two", "three", "thisisjustexampleforwhathappend"] command.Out(my_list.__len__(), my_list) print(command.OutF)
方式二:定义为类方法(推荐)
使用@classmethod装饰器将Out转为类方法,通过第一个参数(惯例命名为cls)访问类属性,更符合Python面向对象设计规范:
class command: OutF = str() @classmethod def Out(cls, outputRange: int, ArgsFormat: list): ArgsFormat[0] = None for i in range(outputRange): cls.OutF += " " + ArgsFormat[i] my_list = ["zero", "one", "two", "three", "thisisjustexampleforwhathappend"] command.Out(my_list.__len__(), my_list) print(command.OutF)
额外优化提示
- 避免用
list作为变量名,它是Python内置类型,会覆盖内置功能,建议改为my_list这类名称 - Python中单行语句不需要加分号
;,可直接删除
内容的提问来源于stack exchange,提问作者Negai
相关产品推荐
相关产品推荐

