简体   繁体   中英

Why is this multi-value data structure not working?

I'm learning about Python data structures, and am looking at this code:

class Student:
    firstname=""
    lastname=""
    grade="U"
    list=[]


student=Student()#create the student
student.firstname=str(input("Input student first name: "))
list.append(student.firstname)
student.lastname=str(input("Input student last name: "))
list.append(student.lastname)
student.grade=str(input("Input student grade: "))
list.append(student.grade)

#print the student data
print("First Name: " + student.firstname)
print("Last Name: " + student.lastname)
print("Grade: " + student.grade)

After the first input for student.firstname , it just says there's an error ( TypeError: descriptor 'append' for 'list' objects doesn't apply to a 'str' object )

What's wrong? I thought the code would just add the firstname to the end of the list, right?

The name list refers to the built-in type. list.append is an unbound method of that type, and has nothing to do with the class attribute named list associated with the class Student .

It would "work" if you passed the appropriate list as the first argument (for reasons I won't get into here)

list.append(student.list, student.firstname)

but you should really be defining additional methods for the class, in addition to the __init__ method that should define the attributes in the first place.

class Student:
    def __init__(self, firstname, lastname, grade):
        self.firstname = firstname
        self.lastname = lastname
        self.grade = "U"

x = input("Input student first name: ")
y = input("Input student last name: ")
z = input("Input student grade: ")

student = Student(x, y, z)
print("First Name: " + student.firstname)
print("Last Name: " + student.lastname)
print("Grade: " + student.grade)

It's not clear what the purpose of the list is, anyway. Do you want to keep a list of instances of Student , perhaps? Do that outside the class. For example,

students = []
student = Student("John", "Doe", "U")
students.append(student)

list=[] and list.append(student.firstname) are one problem: list is a type , not an appropriate object name

I'd recommend backing up to basics and implementing:

  • creation of your class instances with (eg) def __init__(self, first, last, grade)
  • definition of __str__(self) to define how to print() your objects
  • define a list , eg allStudents = []
  • add students to it allStudents.append(Student(first, last, grade))

ref: https://www.w3schools.com/python/python_classes.asp

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