如何让类中的_str____)方法在python中返回此特定值

如何让类中的_str____)方法在python中返回此特定值,python,class,instance,Python,Class,Instance,我有两个班,学生班和一个班。基本上,我可以招收学生,让他们上课。UniClass的\uuuu str\uuuu需要返回一个精确的值,我不知道如何获取它。以下是我目前的代码: class Student(): """ ein Student """ def __init__ (self, name, imt_name, semester): self.name = name self.imt_name = imt_name self

我有两个班,学生班和一个班。基本上,我可以招收学生,让他们上课。UniClass的
\uuuu str\uuuu
需要返回一个精确的值,我不知道如何获取它。以下是我目前的代码:

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}"
当前返回值为:

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

您可能正在使用Python 2运行代码,其中
集合的
str
是:

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(至少在其最新版本中)返回:

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)
),并使用较新的版本