Python类应用问题:输入学号获取学生实例属性的实现
解决方法
你当前的问题在于,代码里只是把Student1.name这类字符串拼接出来,但Python不会自动将字符串解析为变量/属性的引用,所以只会打印文本而非实际属性值。要实现需求,推荐用字典存储学生实例,通过输入的编号快速定位对应实例,再直接访问属性。
修改后的完整代码
class Student: def __init__(self, name, major, gpa, is_on_probation): self.name = name self.major = major self.gpa = gpa self.is_on_probation = is_on_probation # 用字典存储学生实例,键对应输入的编号 students = { 1: Student("Bob Lastname", "Finance", 4.0, False), 2: Student("Firstname Lastname", "CS", 4.0, True) } snum = int(input("Enter Student Number: ")) # 根据输入编号获取对应学生实例 selected_student = students.get(snum) if selected_student: # 直接访问实例的属性并打印 print(selected_student.name, selected_student.major, selected_student.gpa, selected_student.is_on_probation) else: print("Invalid student number")
关键改动说明
- 用字典
students将编号(1、2)和对应的Student实例绑定,避免手动拼接字符串找变量的麻烦。 - 通过
students.get(snum)获取用户指定的学生实例,get方法还能处理输入不存在编号的情况(返回None)。 - 直接访问实例的属性(
selected_student.name等),这才是获取实际属性值的正确方式。
额外优化建议
可以给Student类添加一个print_info方法,让打印属性的逻辑更封装:
class Student: def __init__(self, name, major, gpa, is_on_probation): self.name = name self.major = major self.gpa = gpa self.is_on_probation = is_on_probation def print_info(self): print(self.name, self.major, self.gpa, self.is_on_probation) # 之后调用时只需: if selected_student: selected_student.print_info()
内容的提问来源于stack exchange,提问作者madamon
相关产品推荐
相关产品推荐

