如何将 class 属性的未知长度列表中的每个项目打印为 python 中的字符串?

How can I print each item in an unknown length list that is a class attribute as a string in python?

我有一个 class(学生),具有不同的属性,例如学生 ID、地址和课程。我的str方法为 class returns 用户输入的所有信息。但是,对于列表的属性,例如课程,打印出信息的位置而不是实际信息.这是代码(抱歉有点长,有一堆classes):

class Person:

    __name = None
    __age = None
    __address = None

    def __init__(self, name, age=0, address=None):
        self.set_name(name)
        self.set_age(age)
        self.set_address(address)
  
    def __str__(self):
        return 'Name: ' + self.__name + '\n' + \
               'Age: ' + str(self.__age) + '\n' + \
               'Address: ' + str(self.__address)

    def set_name(self, name):
        self.__name = name    

    def get_name(self):
        return self.__name

    def set_age(self, age):
        self.__age = age

    def get_age(self):
        return self.__age

    def set_address(self, address):
        self.__address = address

    def get_address(self):
        return self.__address

class Student(Person):

    def __init__(self, name, studentID= None, age= 0, address= None):
        super(Student, self).__init__(name, age, address)
        self.set_studentID(studentID)
        self.__courses =[]
    
    def __str__(self):
    
        result = Person.__str__(self)
        result += '\nStudent ID:' + self.get_studentID()
        for item in self.__courses:
            result += '\n   ' + str(item)
        return result
            
    def set_studentID(self, studentID):
        if isinstance(studentID, str) and len(studentID.strip()) > 0:
            self.__studentID = studentID.strip()
        else:
            self.__studentID = 'NA'

    def get_studentID(self):
        return self.__studentID   

    def add_course(self, course):
        print('in add_course')
        self.__courses.append(course)
 
    def get_courses(self):
        for i in range(len(self.__courses)):
            return self.__courses[i]    

class Course:

    __courseName = None
    __dept = None
    __credits = None

    def __init__(self, courseName, dept= 'GE', credits= None):
        self.set_courseName(courseName)
        self.set_dept(dept)
        self.set_credits(credits)
    
    def __str__(self):
        return self.get_courseName() + '/' + self.get_dept() + '/' + str(self.get_credits())

    def set_courseName(self, courseName):
        if isinstance(courseName, str) and len(courseName.strip()) > 0:
            self.__courseName = courseName.strip()
        else:
            print('ERROR: Name must be a non-empty string')
            raise TypeError('Name must be a non-empty string')

    def get_courseName(self):
        return self.__courseName

    def set_dept(self, dept):
        if isinstance(dept, str) and len(dept.strip()) > 0:
            self.__dept = dept.strip()
        else:
            self.__dept = "GE"

    def get_dept(self):
        return self.__dept

    def set_credits(self, credits): 
        if isinstance(credits, int) and credits > 0:
            self.__credits = credits
        else:
            self.__credits = 3

    def get_credits(self):
        return self.__credits

students = []

def recordStudentEntry():   
    
    name = input('What is your name? ')
    age = input('How old are you? ')
    studentID= input('What is your student ID? ')
    address = input('What is your address? ')
    s1 = Student(name, studentID, int(age), address)
    students.append(s1)
    s1.add_course(recordCourseEntry())
    print('\ndisplaying students...')
    displayStudents()
    print()        

        
def recordCourseEntry():
    courses = []
    for i in range(2):
        courseName = input('What is the name of one course you are taking? ')
        dept = input('What department is your course in? ')
        credits = input('How many credits is this course? ')
        c1 = Course(courseName, dept, credits)
        print(c1)
        courses.append(c1)
  
    displayCourses(courses)
    return courses
    
def displayCourses(courses):
    print('\ndisplaying courses of student... ')
    for c in range(len(courses)):
        print(courses[c])
    
def displayStudents():
    for s in range(len(students)):
        print()
        print(students[s])

recordStudentEntry()

上面的代码是这样打印出 'displaying students...' 部分的:

displaying students...

Name: sam
Age: 33
Address: 123 st
Student ID:123abc
   [<__main__.Course object at 0x000002BE36E0F7F0>, <__main__.Course object at 
0x000002BE36E0F040>]

我知道它正在打印位置,因为我需要在列表中建立索引。但是,列表的长度每次都会不同。通常如果我想索引一个列表,例如,打印一个名字列表,我会这样做:

listOfNames = ['sam', 'john', 'sara']
for i in range(len(listOfNames)):
    print(listOfNames[i])

listOfNames = ['sam', 'john', 'sara']
for i in listOfNames:
    print(i)

(不确定这两种方式之间是否存在差异,因为它们的打印方式相同:)

sam
john
sara

如何在我的 class 的 str 方法中编写类似索引到列表技术的内容,以便它打印信息而不是位置?

最好遵守 Python 的标准约定,例如命名 具有单下划线而不是双下划线的对象的私有属性。 后者保留用于 Python “内部”属性和方法。 此外,约定使用 get/set 方法的对象的对象属性, 不是 class 属性。这将使您更容易检查您的对象,同时 仍然保持数据隐藏。示例:

class Course:
    def __init__(self, courseName, dept= 'GE', credits= None):
        self._courseName = None
        self._dept = None
        self._credits = None
        self.set_courseName(courseName)
...

关于为什么课程没有按照您预期的方式打印出来的问题 根源于您对录音进行编程的方式存在编程错误 当然。在recordCourseEntry()中,你录制了两门课程并把它们 在列表中。但是,您使用方法将其传递给 Student 对象 一次用于一门课程。我建议的修复方法是:

...
    # s1.add_course(recordCourseEntry())
    courses = recordCourseEntry()
    for course in courses:
        s1.add_course(course)
...

这可能足以让您继续前进。我得到的示例输出是:

Name: Virtual Scooter
Age: 33
Address: 101 University St.
Student ID:2021
   ff/GE/3
   gg/GE/3