从编码能力的角度来看,我仍然处于“我的婴儿期”,最近我做了一个简单的类/对象上下文。不知道如何从多个属性中打印详细信息,在这里寻求帮助。
在Windows PC上尝试更好地使用Python 3时,我创建了student.py和object.py。前者包含self。,而后者列出student1,student2 ... studentn的实际特征。但是,我似乎只能为那个学生打印student1.gpa
,student1.major
和许多其他Student1特性。除了学生1的特征外,我该如何打印?
class Student:
def __init__(self, name, major, physicsLevel, mathLevel, chemistryLevel, gpa, is_on_probation):
self.name = name
self.physicsLevel = physicsLevel
self.mathLevel = mathLevel
self.chemistryLevel = chemistryLevel
self.major = major
self.gpa = gpa
self.is_on_probation = is_on_probation
def on_honor_roll(self): # function placed inside a class, in this case, whether student is on honor roll through the level of gpa
if self.gpa >= 3.5:
return True
else:
return False
from Student import Student
student1 = Student("Jim, ", "GeoPhysics and Space", "A", "A", "B", 3.1, "False")
student2 = Student("Ann, ", "Design and Innovation, ", "A, ", "A, ", "B", 4.2, "True")
问题:在下面尝试过,但是没有一种更聪明的方法来打印所有学生或所有gpa结果吗? -另外,为什么第2行从一个字符开始缩进,在下面尝试打印?
print(student1.name, student1.major, student1.physicsLevel, student1.gpa, '\r\n', student2.name, student2.major, student2.physicsLevel, student2.gpa)
答案 0 :(得分:1)
在学生类中创建一个__str__
方法,该方法返回具有所需格式的字符串:
....
def __str__(self):
return f"{self.name}, {self.major}, {self.gpa}"
...
然后循环遍历学生:
for student in (student1, student2):
print(student)