Pajke
Pajke

Reputation: 405

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

I have 2 classes, Student and UniClass. Basically, I can enroll students and put them in classes. The __str__ of UniClass needs to return an exact value, and I don't know how to get to it. Here's my code so far:

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)

These are my asserts:

# 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}"

The current return value is:

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

Upvotes: 2

Views: 88

Answers (1)

Thierry Lathuille
Thierry Lathuille

Reputation: 24289

You are probably running your code with Python 2, in which the str for a set is:

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])'

While (at least in its recent versions) 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}'

as expected by your asserts.

Check what version you are really executing (import sys; print(sys.version)), and use a more recent one!

Upvotes: 1

Related Questions