Uncategorized

Utilisation des property et setter en python – Python Help



class Bibliotheque:
def init(self, nom, livres_nombre=0):
self._nom = None
self.nom = nom
self._livres_nombre = livres_nombre
self._livres_empruntes = 0

@property
def nom(self):
    return self._nom

@nom.setter
def nom(self, valeur):
    if not valeur:
        raise ValueError("Le nom ne peut pas être une chaîne vide.")
    self._nom = valeur

@property
def livres_nombre(self):
    return self._livres_nombre

@livres_nombre.setter
def livres_nombre(self, valeur):
    if valeur < 0 or valeur < self._livres_empruntes:
        raise ValueError("Nombre de livres invalide.")
    self._livres_nombre = valeur

@property
def livres_empruntes(self):
    return self._livres_empruntes

@property
def livres_disponibles(self):
    return self._livres_nombre - self._livres_empruntes

def emprunter_livre(self, quantite):
    if quantite < 0 or quantite > self.livres_disponibles:
        raise ValueError("Quantité invalide pour l'emprunt.")
    self._livres_empruntes += quantite

def retourner_livre(self, quantite):
    if quantite < 0 or quantite > self._livres_empruntes:
        raise ValueError("Quantité invalide pour le retour.")
    self._livres_empruntes -= quantite

def __str__(self):
    return f"{self.nom}, Livres nombre: {self.livres_nombre}, Livres disponibles: {self.livres_disponibles}, Livres empruntés: {self.livres_empruntes}"

biblio = Bibliotheque(“MaBiblio”, 100)
print(biblio)
biblio.emprunter_livre(10)
print(biblio)
biblio.retourner_livre(5)
print(biblio)

Hi !

Is there anything wrong with your code ? Are you looking for feedback ? Or maybe just showing it off ?



1 Like

Please read the pinned thread in order to understand how to make the code show up properly; then, if you have a question or need other help with the code, please actually ask the question, tell us what problem you encountered, etc.

The initialisation function should be __init__ instead of init.

It is presumably __init__ in the actual code. That’s why it shows up in boldface in the post: outside of multi-line formatted code blocks, double underscores have that effect in the forum’s Markdown.



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *