0

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

Apex Predator
  • 171
  • 1
  • 3
  • 13
  • Not working how? What isn't working the way you expect? – John Kugelman Apr 03 '15 at 20:28
  • This is what i get when i try to list the dictionary <__main__.Etudiant object at 0x000000000330BCC0> – Apex Predator Apr 03 '15 at 20:30
  • Read this: http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python – Nir Alfasi Apr 03 '15 at 20:32
  • You should implement a `__repr__` method for your class. That function should output all the relevant information that your class contains (i.e. student number and course number list). The linked SO talks about the difference between that and implementing a `__str__` method, but the implication was that you need one of those. `__str__` falls back on `__repr__` so if you only implement one, it'd be `__repr__` – geoelectric Apr 03 '15 at 20:44

1 Answers1

3

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
Ben
  • 6,687
  • 2
  • 33
  • 46