
python 小萌新遭遇 attributeerror 错误
问题背景
一位新手在编写 python 代码时,尝试获取自己定义的模块中函数的返回值,但遇到 attributeerror 错误。
错误详情
立即学习“Python免费学习笔记(深入)”;
attributeerror: module '__main__' has no attribute 'student'
代码示例
class student: def __init__(self, name): self.name = nameclass manager: def __init__(self, name): self.name = namedef 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’”?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1350695.html
微信扫一扫
支付宝扫一扫