Home > Net >  How do I write a class that uses objects of another class and puts them in a set?
How do I write a class that uses objects of another class and puts them in a set?

Time:12-12

This is for an assignment. So there are two classes. The first is Student, which creates Students with a Name, an Username and the semester theyre in. I got the first class to work pretty effortlessly, but the second one calles UniClass is hard to do. It creates a University class and gives it a name. Then it can enroll Students into the class. It is supposed to put them into a set. If it is empty the method "str" shall return "set()" and if not then it shall return the set.

class Student:
    def __init__(self,name,imt_name,semester):
        """
        Constructor
        """
        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):
        """
        Constructor
        """
        self.name=name
    def enroll_student(self,students):
        self.students=Student.str()
        global x
        x=True
    def __str__(self):
        if x==True:
            return (students) 
        else:
            return("set()")

I messed up at the second class.

CodePudding user response:

I presume UniClass maintains a set of Student objects, which means it's the responsibility of whoever calls UniClass.enroll_student to provide an instance of Student, rather than enroll_student needing to create a new student. Something like

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

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

    def __str__(self):
        return ",".join(str(s) for s in self.students)

c = UniClass("math")
c.enroll_student(Student("john", "doe", "fall"))
c.enroll_student(Student("alice", "smith", "fall"))
  • Related