如何在 Python 中打印()列表中的对象

How to print() an object in list in Python

我将我的对象存储在一个列表中,然后当我打印出来时,它显示如下:

<__main__.Student object at 0x7f76d80d8198>

这是我的代码:

class Student:
    def __init__(self, std_id, std_name, std_dob, std_mark=0):
        self.student_id = std_id
        self.student_name = std_name
        self.student_dob = std_dob
        self.student_mark = std_mark

    def input(self, std_id, std_name, std_dob, std_mark):
        student = Student(std_id, std_name, std_dob,std_mark)
        Students.append(student)

如您所见,“学生”是我的列表,我的列表附加了对象“学生”。但是,我可以使用这个功能

def list_student(self, student):
        print("ID: ", student.student_id)
        print("Name: ", student.student_name)
        print("Dob: ", student.student_dob)
        print("GPA: ",student.student_mark)
        print("\n")

观察我的对象,但我想在我的列表中看到它带有“print(Students)”。谁能建议怎么做?非常感谢!

在 class 中使用 __str__ 函数(您的代码需要一些修改,也许现在仍然如此):

class Student:
    def __init__(self, std_id, std_name, std_dob, std_mark=0):
        self.student_id = std_id
        self.student_name = std_name
        self.student_dob = std_dob
        self.student_mark = std_mark

    def input(self, std_id, std_name, std_dob, std_mark):
        student = Student(std_id, std_name, std_dob,std_mark)
        Students.append(student)

    def __str__(self):
        toShow = ""
        toShow += "ID: "+ str(self.student_id) + "\n"
        toShow += "Name: "+ str(self.student_name) + "\n"
        toShow += "Dob: "+ str(self.student_dob) + "\n"
        toShow += "GPA: "+ str(self.student_mark) + "\n"
        toShow += "\n"
        return toShow

例子

exmStudent = Student(1234, "Amir", "Std_dob", -20)
print(exmStudent)

输出

ID: 1234
Name: Amir
Dob: Std_dob
GPA: -20

list_student 函数转换为 Student 上的 __repr__ 方法:

class Student:
    def __init__(self, std_id, std_name, std_dob, std_mark=0):
        self.student_id = std_id
        self.student_name = std_name
        self.student_dob = std_dob
        self.student_mark = std_mark

    def __repr__(self):
        return (
            f"ID: {self.student_id}\n"
            f"Name: {self.student_name}\n"
            f"Dob: {self.student_dob}\n"
            f"GPA: {self.student_mark}\n"
        )

现在任何时候你 print Student (即使在列表中),你都会得到一个具有该格式的字符串而不是默认的 <__main__.Student object at xxxxx> 格式。