简体   繁体   English

在类中定义一个列表并调用它并在python的函数中使用它

[英]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.我是 python 中的类和对象的新手,需要帮助。 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.这个对象应该存储班级编号(如 001)、它所在的学期(如“fall”)以及学生获得的成绩。 I am stuck with “Class taken” attribute.我坚持使用“Class taken”属性。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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