Python Forum
Class and calling a method
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Class and calling a method
#1
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)
Reply
#2
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()
Reply
#3
Did you get this figured out, or are you still needing help?
Reply
#4
I got it thanks!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Please, how do I call the method inside this class Emekadavid 1 1,632 Jun-26-2020, 01:26 PM
Last Post: Yoriz
  class method on two object gabejohnsonny21 4 2,433 Apr-22-2020, 06:57 AM
Last Post: DeaD_EyE
  Calling an class attribute via a separate attribute in input wiggles 7 2,874 Apr-04-2020, 10:54 PM
Last Post: wiggles
  Class/Method Confusion ramadan125 1 2,597 Sep-10-2018, 12:19 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020