简体   繁体   中英

Define a list in class and call it and use it in a function in python

I am new to classes and objects in python and in need of help. I need to create a student class with the attributes "Classes taken". This object should store the class number (like 001), the semester it was taken it (like “fall”), and the grade the student obtained. I am stuck with “Class taken” attribute. I don't understand if I have to create a list or define it some other manner.

Basically, I am unable to define a list and call it and use it in a function.

and error is

NameError: name 'self' is not defined

Thanks in advance for help :)

class Student(object):

def __init__(self, number,ClassNumber,Semester,Grade):
    self.number = number
    self.classTaken=[]

def register():
  ClassNumber = input('Enter ClassNumber:  ')
  Semester = input('Enter Semester:  ')
  Grade = input('Enter Grade:  ') 
  print(self.classTaken.append(Student(Semester)))

student1= Student.register(self.classTaken)

You can try this one

class Student():
    def __init__(self):
        self.classTaken = []

    def register(self,Number,ClassNumber,Semester,Grade):
        self.classTaken.extend((Number,ClassNumber,Semester,Grade))

student1 = Student()
student1.register(4,2,6,8)
print(student1.classTaken)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM