Python 小萌新:为什么我的代码提示“AttributeError: module \’__main__\’ has no attribute \’Student\’”?
你在学习相关的知识吗?本文《Python 小萌新:为什么我的代码提示“AttributeError: module \’__main__\’ has no attribute \’Student\’”?》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!
python 小萌新遭遇 attributeerror 错误
问题背景
一位新手在编写 python 代码时,尝试获取自己定义的模块中函数的返回值,但遇到 attributeerror 错误。
错误详情
attributeerror: module '__main__' has no attribute 'student'
代码示例
class student: def __init__(self, name): self.name = name class manager: def __init__(self, name): self.name = name def main(): # ... if cls == 'student': obj = student.cls(ret['username']) # 根据类名实例化对象 else: obj = manager.cls(ret['username'])
错误分析
在上述代码中,问题出现在第 12 行和 14 行,即在实例化 student 和 manager 对象时。在 python 中,类属性和方法只能通过类名直接访问。但在本示例中,却使用 student.cls 和 manager.cls 来访问它们。
在 python 中,__main__ 模块表示当前正在运行的脚本,其属性和方法只能通过 __main__ 模块直接访问。因此,在 __main__ 模块外,无法通过 student.cls 或 manager.cls 访问类属性和方法,会导致 attributeerror 错误。
解决方案
正确的应该使用以下方式实例化对象:
if cls == 'Student': obj = Student(ret['username']) else: obj = Manager(ret['username'])
到这里,我们也就讲完了《Python 小萌新:为什么我的代码提示“AttributeError: module \’__main__\’ has no attribute \’Student\’”?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注公众号,带你了解更多关于的知识点!