如何使用For循环打印python类中的所有项目

时间:2018-11-26 01:04:09

标签: python loops class for-loop

我创建了一个新班级:

testing.py:

class student:
    def __init__(self, name, major, gpa):
        self.nm = name
        self.mj = major
        self.gp = gpa

然后,我将其移至工作文件testing.py:

from testing import student
student1=student("Marcos","Physics",3.99)
student2=student("Phillyp","Biology",2.99)
student3=student("Naim", "Architecture", 3.42)

for k in range(1,4):
    print(student(k).gp) <------- how do I merge this string with int!?!?

我的最终目标是打印出所有学生的所有gpa,所以我知道我需要这样做

print(student1.gp)
print(student2.gp)
print(student3.gp)

那么我如何将k连接到变量名中,以生成Student1.gp,student2.gp等?

非常感谢大家!

2 个答案:

答案 0 :(得分:3)

您想遍历所有学生的名单,而不是for k in range(1,4):

students = [student1, student2, student3]
for student in students:
    print(student.gp)

编辑

如果您希望能够按名称引用学生,请将其存储在dict中:

students = {'student1': student("Marcos","Physics",3.99),
            'student2': student("Phillyp","Biology",2.99),
            'student3': student("Naim", "Architecture", 3.42)}

for i in range(1, 4):
    print(students[f'student{i}'].gp)
    # if less than python 3.6
    # print(students['student{}'.format(i)].gp)

答案 1 :(得分:1)

您应该做的是将所有对象放入list中。例如

from testing import student

student1 = student("Marcos","Physics",3.99)
student2 = student("Phillyp","Biology",2.99)
student3 = student("Naim", "Architecture", 3.42)

students = [student1, student2, student3]

for student in students:
    print(student.gp)