Python Forum

Full Version: Class and calling a method
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
class student:
    
    def __init__(self, first_name, last_name, student_id, year):
        self.first_name = first_name
        self.last_name = last_name
        self.student_id = student_id
        self.year = year
        self.course = []
        
    def __str__(self):
        return self.first_name, self.course
        
    def enroll(self, course):
        self.course = course
    


def main():
    
    file = student('John', 'Smith', 'L01234567', 'senior')
    print(file)
    file.enroll ('CSC225')
    


    
main()
so when I call enroll on 'CSC225' I want it to print “John is enrolled in CSC225.” But I cannot figure out what I am doing wrong. I just threw in the print statement to test it out but it is not working the way I thought it should. This is the latest error I have been getting when with what I have last tried to get it to work:
Error:
line 22, in main print(file) builtins.TypeError: __str__ returned non-string (type tuple)
You need to construct the string in the __str__ method if that is what you want it to look like.
Also you need to decide if Student.course is a list or a single item.

class Student(object):
    def __init__(self, first_name, last_name, student_id, year):
        self.first_name = first_name
        self.last_name = last_name
        self.student_id = student_id
        self.year = year
        self.course = []
         
    def __str__(self):
        return "{} is enrolled in {}.".format(self.first_name, self.course)
         
    def enroll(self, course):
        self.course.append(course)
     
 
def main():
    student = Student('John', 'Smith', 'L01234567', 'senior')
    student.enroll('CSC225')
    print(student)
     

main()
Did you get this figured out, or are you still needing help?
I got it thanks!