这(学生)是从哪里来的

2024-09-30 12:31:06 发布

您现在位置:Python中文网/ 问答频道 /正文

class Student:
    def __init__(self,name,age,grade): #giving the attributes
        self.name=name
        self.age=age
        self.grade=grade

    def get_grade(self):
        return self.grade

class Course:
    def __init__(self,lesson,max_student):#giving attributes
        self.lesson=lesson
        self.max_student=max_student
        self.students=[]

    def add_student(self,student):
        if len(self.students)<self.max_student:
            self.students.append(student) #append(student) from where
            #I don't get where the append(student) get the name from.
            #As above code did't use student.
            return True
        return False

s1=Student('Tim',19,95) #Naming the student
s2=Student('bill',19,75)
s3=Student('jill',19,65)

course1=Course('Math',2)
course1.add_student(s1) #Adding the Student to a list by appending
course1.add_student(s2)

print(course1.students[0].name)
#Will give Tim but how do i print them all at once
#instead of multiple print maybe like a [0:1] but got error

Tags: thenameselfaddagegetreturndef
1条回答
网友
1楼 · 发布于 2024-09-30 12:31:06
  • append方法是Python的一部分。它是list类的一部分,因此所有列表都有此方法(以及其他方法)。检查docs。您在self.students = []行中将self.students设置为空的列表

  • student变量来自add_student的参数,如您在此处指定的:def add_student(self,student)。因此,当您调用course1.add_student(s1)时,s1将在方法内student(因为对于类方法,第一个参数self始终是类实例本身,不必在调用中指定)

相关问题 更多 >

    热门问题