Reputation: 43
Still in 'my infancy' from a coding capability perspective, I recently did a simple class/object context. Don't know how to print details from more than one attribute, looking for assistance here.
Working on a Windows PC in my attempt to get wiser on Python 3, I created a student.py and object.py. The former contains self.'s while the latter lists actual characteristics of student1, student2....studentn. Yet I seem only to be able to print student1.gpa
, student1.major
and a number of other student1 characteristics for THAT student only. How do I print more than student1 characteristics?
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")
QUESTION: Tried below, but isn't there a smarter way to print all students or all gpa results? - also, why does line 2 start indented with one character, doing below attempt to print?
print(student1.name, student1.major, student1.physicsLevel, student1.gpa, '\r\n', student2.name, student2.major, student2.physicsLevel, student2.gpa)
Upvotes: 0
Views: 54
Reputation: 42678
Create a __str__
method in the student class that returns a string with the formatting you want:
....
def __str__(self):
return f"{self.name}, {self.major}, {self.gpa}"
...
Then just loop over the students:
for student in (student1, student2):
print(student)
Upvotes: 1