
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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号