如何将 class 中的 __str__ 方法转换为 return python 中的这个特定值

How do I get my __str__ method in a class to return this specific value in python

我有 2 个 类,Student 和 UniClass。基本上我可以招收学生,放在类。 UniClass 的 __str__ 需要 return 一个确切的值,我不知道如何得到它。到目前为止,这是我的代码:

class Student():
    """ ein Student """

    def __init__ (self, name, imt_name, semester):
        self.name = name
        self.imt_name = imt_name
        self.semester = semester

    def __str__(self):
        return "{} {}{}{} in Semester {}".format(self.name, "[", self.imt_name, "]", self.semester)


class UniClass:


    def __init__(self, name):
        self.name = name
        self.students = set()

    def enroll_student(self, student):
            self.students.add(student)

    def __str__(self):
        a = set()

        if len(self.students) == 0:
            return "set()"
        else:
            for student in self.students:
               a.add(str(student))

        return str(a)

这些是我的断言:

# Student str
student_horst = Student("Horst", "horst99", 20)
assert str(student_horst) == "Horst [horst99] in Semester 20"
# UniClass str
programming_class = UniClass("Programmieren")
assert str(programming_class) == "set()"

programming_class.enroll_student(student_horst)
assert str(programming_class) == "{Horst [horst99] in Semester 20}"

student_horst = Student("Horst2", "horst100", 20)
student_horst2 = Student("Horst2", "horst100", 20)

programming_class.enroll_student(student_horst2)
assert str(programming_class) == "{Horst [horst99] in Semester 20, Horst2 [horst100] in Semester 20}" \
   or str(programming_class) == "{Horst2 [horst100] in Semester 20, Horst [horst99] in Semester 20}"

当前return值为:

set(['Horst [horst99] in Semester 20', 'Horst2 [horst100] in Semester 20'])

您可能 运行 您的代码 Python 2,其中 setstr 是:

Python 2.7.16 (default, Apr  9 2019, 04:50:39) 
[GCC 8.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> str({1, 2})
'set([1, 2])'

虽然(至少在最近的版本中)Python 3 returns:

Python 3.8.0 (default, Nov 21 2019, 17:20:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> str({1, 2})
'{1, 2}'

如您所料。

检查您实际执行的版本 (import sys; print(sys.version)),并使用更新的版本!