Apex Predator
Apex Predator

Reputation: 171

Output a dict in python

Hi guys i'm struggling with these classes.
this is what i have to do: cours stands for course and etudiant stands for student. I have to create a class Student that will do the following and i also have to use repr. so create object with student number and add courses

>>> d = Etudiant(12456)
>>> d.addCours('csi2520')
>>> d.addCours('csi2772')
>>> d.addCours('csi2510')
>>> d
12456:[ 'csi2520', 'csi2772', 'csi2510']
>>> d.cours('csi2510')
True
>>> d.cours('csi4900')
False

This is what i did but it's not working

class Etudiant:
    cours=[]
    def __init__(self, numero):
        self.numero=numero
        self.classe={self.numero:self.cours}
        repr(self.classe)
    def addCours(self, cours1):
        self.cours.insert(-1,cours1)

please keep it simple i'm a newbie

Upvotes: 0

Views: 112

Answers (1)

Ben
Ben

Reputation: 6777

To alter how a Python object looks when it's printed, you need to implement a magic method called __repr__ (short for representation). You also don't need to store the student number inside the cours variable:

class Etudiant(object):
    def __init__(self, numero):
        self.numero = numero
        self._cours = []
    def addCours(self, cours):
        self._cours.append(cours)
    def cours(self, cours):
        return cours in self._cours
    def __repr__(self):
        return '{}: {}'.format(self.numero, self._cours)

Testing:

>>> d = Etudiant(12456)
>>> d.addCours('csi2520')
>>> d.addCours('csi2772')
>>> d.addCours('csi2510')
>>> d
12456: ['csi2520', 'csi2772', 'csi2510']
>>> d.cours('csi2510')
True
>>> d.cours('csi4900')
False

Upvotes: 3

Related Questions