Python 小萌新:为什么我的代码提示“AttributeError: module '__main__' has no attribute 'Student'”?

DDD
发布: 2024-10-31 09:54:01
原创
561人浏览过

python 小萌新:为什么我的代码提示“attributeerror: module \'__main__\' has no attribute \'student\'”?

python 小萌新遭遇 attributeerror 错误

问题背景

一位新手在编写 python 代码时,尝试获取自己定义的模块中函数的返回值,但遇到 attributeerror 错误。

错误详情

立即学习Python免费学习笔记(深入)”;

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'”?的详细内容,更多请关注php中文网其它相关文章!

豆包AI编程
豆包AI编程

智能代码生成与优化,高效提升开发速度与质量!

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号