[Tutor] Would you please help me understand my error

Marco Rompré marcodrompre at gmail.com
Sat Apr 24 03:10:22 CEST 2010


Bien,

>    for starters please get rid of all those set_ methods. They are
> doing nothing, it's not pythonic. Just assign the value straight away.
> e.g.: from """ item01.set_prix("999.99") """  to """ item01.prix =

"999.99" """
>

    Our teacher showed us this method and in our exercise we had to copy the
teacher's code and modify the data to fit our concept

    But thks I found my error but what did you say about th decimal module
    we have to keep in mind that my exercise is for an introductory course
in python I am not good, I am  trying to learn at my best.

Here's my new code( can you please tell me if it is okay)

class Magasin:
    """
    Le concept magasin pour la gestion d'inventaire des items de golf.
    """
    def __init__(self, nom ="", items =[] ):
        self.nom = nom
        self.items = items

    def set_nom(self, nom):
        self.nom = nom

    nom = property(None, set_nom)

    def set_items(self, items):
        self.items = items

    items = property(None, set_items)

    def __str__(self):
        return self.nom

class Item:
    """
    Le concept item pour la gestion d'inventaire des items de golf.
    """
    def __init__(self, nom ="", prix =""):
        self.nom = nom
        self.prix = prix

    def set_nom(self, nom):
        self.nom = nom

    nom = property(None, set_nom)

    def set_prix(self, prix):
        self.prix = prix

    prix = property(None, set_prix)

    def __str__(self):
        return self.nom

class Modele:
    """
    La definition d'un modele avec les magasins.
    """
    def __init__(self, magasins =[]):
        self.magasins = magasins

    def set_magasins(self, magasins):
        self.magasins = magasins

    magasins = property(None, set_magasins)


    def sauvegarder(self,nom_fichier):
        modele_fichier = open(nom_fichier, 'w')
        for magasin in self.magasins:
            modele_fichier.write("===MAGASIN==="  + "\n")
            modele_fichier.write("nom : " + magasin.nom + "\n")
            modele_fichier.write("items : " + "\n")
            for item in magasin.items:
                modele_fichier.write("    ---ITEM---"  + "\n")
                modele_fichier.write("    nom : " + item.nom + "\n")
                modele_fichier.write("    prix : " + item.prix + "\n")
                modele_fichier.write("    ---FIN ITEM---"  + "\n")
            modele_fichier.write("===FIN MAGASIN==="  + "\n")
        modele_fichier.close()

    def charger(self, nom_fichier):
        magasins = []
        try:
            modele_fichier = open(nom_fichier, 'r')
        except IOError:
            print("Le fichier " + nom_fichier + " n'existe pas.")
        else:
            fin_fichier = False
            while not fin_fichier:
                ligne = modele_fichier.readline()
                if ligne == "":
                    self.set_magasins(magasins)
                    modele_fichier.close()
                    fin_fichier = True
                    break
                magasin = Magasin()
                items = []
                fin_magasin = False
                while not fin_magasin:
                    ligne = modele_fichier.readline().strip()
                    if ligne.startswith("===FIN MAGASIN==="):
                        magasin.set_items(items)
                        magasins.append(magasin)
                        fin_magasin = True
                    elif ligne.startswith("nom"):
                        nom = ligne.split(':')[1]
                        magasin.set_nom(nom.strip())
                    elif ligne.startswith("---ITEM---"):
                        item = Item()
                        fin_item = False
                        while not fin_item:
                            ligne = modele_fichier.readline().strip()
                            if ligne.startswith("nom"):
                                nom = ligne.split(':')[1]
                                item.set_nom(nom.strip())
                            elif ligne.startswith("prix"):
                                prix = ligne.split(':')[1]
                                item.set_prix(prix.strip())
                            elif ligne.startswith("---FIN ITEM---"):
                                items.append(item)
                                fin_item = True




    def vide(self):
        if self.magasins == []:
            return True
        else:
            return False

    def initialiser(self, nom_fichier):
        magasin01 = Magasin ("Swing de golf")

        item01 = Item ("Ensemble de fers Titleist")
        item01.set_prix("999.99")

        item02 = Item ("Ensemble de fers Callaway")

        items = [item01, item02]
        magasin01.set_items(items)

        self.set_magasins([magasin01])

        self.sauvegarder(nom_fichier)

    def afficher(self):
        print("")
        print("Magasins")
        for magasin in self.magasins:
            print("")
            print(magasin)
            for item in magasin.items:
                print(item)


if __name__ == '__main__':
    modele = Modele()
    nom_fichier = "magasinmodele.txt"
    modele.charger(nom_fichier)
    if modele.vide():
        modele.initialiser(nom_fichier)
    modele.afficher()




> BTW, why do you use prix as a character? Shouldn't it be a number? Check
> the decimal module.
> Your error comes from the fact that magasin01 only exists inside
> initialiser(), it is local to this method, so afficher() can't reference
> it.
> Note : notice the """ print(tache) """ correction. The code is untested
> and probably compliant with 2.5 and not 3.x
>
>  from decimal import Decimal
>
> Thank You in advance


-- 
Marc-O. Rompré
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100423/3ac29f83/attachment-0001.html>


More information about the Tutor mailing list