Search code examples
python-3.xfunctionclassself

I'm supposed to create database class of student.I have to create a function which adds courses accounting for addition in attributes of the object


class student:
    def __init__(self, class_student, name, GPA=0,number_of_course=0, number_of_credits=0):
        self.class_student= class_student 
        self.name= name
        self.GPA= GPA
        self.number_of_course=number_of_course
        self.number_of_credits= number_of_credits
    def add_course(self,GPA, number_of_credits):
        return student(self.class_student,self.name, self.GPA,self.number_of_course,self.number_of_credits)


mylad= student('Senior', 'Ardy', 2.7, 0, 0)



print(mylad.add_course(3.2, 3))

This code displays <main.student object at 0x7ff427458460>. I am a beginner at Python and do not know how to fix this. If anyone can help me I would appreciate it very much!


Solution

  • I believe that you are just trying to re-assign a different value the existing self attributes of the Student class. In this case, you shouldn't use return statements, instead re-assign the class attributes themselves.

    class Student:
    
        def __init__(self, class_student, name, GPA=0, num_courses=0, num_credits=0):
            self.class_student = class_student 
            self.name = name
            self.GPA = GPA
            self.num_courses = num_courses
            self.num_credits = num_credits
    
        def add_course(self, GPA, num_credits):
            self.GPA = GPA
            self.num_credits = num_credits
    
    sample_student = Student('Senior', 'Ardy', 2.7, 0, 0)
    sample_student.add_course(3.2, 3)
    
    print(sample_student.GPA)
    print(sample_student.num_courses)
    ...
    

    Alternatively, you could elimate the add_course classmethod and just do this:

    class Student:
    
        def __init__(self, ...):
            ...
    
    sample_student = Student("Senior", "Ardy", 2.7, 0, 0)
    sample_student.GPA = 3.2
    sample_student.num_credits = 3
    ...