我应该创建 student.I 的数据库 class 必须创建一个函数来添加课程,以说明对象属性的添加

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))

此代码显示 <main.student object at 0x7ff427458460>。 我是 Python 的初学者,不知道如何解决这个问题。如果有人能帮助我,我将不胜感激!

我相信您只是想为 Student class 的现有 self 属性重新分配一个不同的值。在这种情况下,您不应使用 return 语句,而应重新分配 class 属性本身。

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)
...

或者,您可以省略 add_course class 方法,只需执行以下操作:

class Student:

    def __init__(self, ...):
        ...

sample_student = Student("Senior", "Ardy", 2.7, 0, 0)
sample_student.GPA = 3.2
sample_student.num_credits = 3
...