首页 新闻 会员 周边

python 小萌新遭遇AttributeError错误

0
悬赏园豆:5 [已解决问题] 解决于 2018-08-06 17:52

  我想获取我自己写的模块里的某一个函数的返回值,但是提示AttributeError错误

  错误详情:AttributeError: module '__main__' has no attribute 'Student'

  具体代码:

 1 import sys
 2 from core import enter
 3 from core import student
 4 from core import manager
 5 flag0 = 1
 6 def main():
 7     print('\033[1;34m欢迎进入学生选课系统\033[0m'.center(50,'*'))
 8     ret = enter.login()
 9     if ret:
10         cls = getattr(sys.modules['__main__'], ret['status'])       # 得到类名
11         if cls == 'Student':
12             obj = student.cls(ret['username'])     # 根据类名实例化对象
13         else:
14             obj = manager.cls(ret['username'])
15         while flag0:
16             if ret['status'] == 'Student':
17                 print('\033[1;34m学生选课系统:学生端\033[0m'.center(50,'*')+'\n')
18                 print(('\033[1;34m当前登录用户:%s\033[0m' % obj.name).center(50))
19             else:
20                 print('\033[1;34m学生选课系统:管理员端\033[0m'.center(50, '*')+'\n')
21             for key,item in enumerate(cls.li,1):
22                 print(str(key).center(20),item[0])
23             num = int(input('\n输入您要做的操作序号:'))
24             if num <= len(cls.li):
25                 getattr(obj,cls.li[num-1][1])()
26             else:
27                 print('\033[1;32m\n你的输入有误,请重新输入!\033[0m')

  出现错误的是第10行,很茫然,不知道为什么会出现这个错误.请大神指点一下

清风吹杨柳的主页 清风吹杨柳 | 初学一级 | 园豆:24
提问于:2018-08-06 16:51
< >
分享
最佳答案
1

为什么不把cls打印出来看看呢?

收获园豆:5
丁壮 | 菜鸟二级 |园豆:219 | 2018-08-06 17:27

右边就是错误的,执行不到赋值

清风吹杨柳 | 园豆:24 (初学一级) | 2018-08-06 17:29

@清风吹杨柳: getattr是返回一个对象的属性值,

getattr(objectname[, default])

Return the value of the named attribute of objectname must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent tox.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

 

https://docs.python.org/3/library/functions.html#getattr   

丁壮 | 园豆:219 (菜鸟二级) | 2018-08-06 17:36

@丁壮: 大哥,对不起,我错了,我这就去学英语

清风吹杨柳 | 园豆:24 (初学一级) | 2018-08-06 17:38

@清风吹杨柳: 额....就是,getattr(对象,名称) 返回这个对象属性名的值,name这里必须是字符串,

getattr(x,'foobar') 相当于,x.foobar      你这里报错的原因是因为没有Student这个属性(ret['status']的结果应该是Student)

丁壮 | 园豆:219 (菜鸟二级) | 2018-08-06 17:43

@丁壮: 感谢解惑,谢谢您的指点,解决了

清风吹杨柳 | 园豆:24 (初学一级) | 2018-08-06 17:52

@清风吹杨柳: 客气了

丁壮 | 园豆:219 (菜鸟二级) | 2018-08-06 17:54
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册