Object Oriented Programming - Attributes and Methods in Classes - Additional Exercise
Intro
Jusqu'ici dans notre parcours sur le thème des Class (classes), on a appris à les reconnaître et à les construire avec des attributs et des méthodes. Il ne nous manque plus qu'un peu de pratique.
Content
✅ Dans cette quête, tu vas t'entraîner, c'est en forgeant qu'on devient forgeron !

Progressons ensemble !
Avant de continuer, assure-toi que tous les sujets abordés dans la quête précédente sont bien clairs.
On va continuer avec l'exemple du chat Tamagochi commencé dans la quête précédente. Si tu n'es pas sûre de quelle partie du code on va réutiliser, tu peux la retrouver ici.
Le dilemme de Schrödinger : le chat est-il vivant ?
Le chat de Schrödinger est une expérience qui illustre un paradoxe de la physique quantique. La question principale était « le chat est-il vivant ou mort ? » et aucune réponse définitive n'était donnée. Dans notre code, c'est pareil : jusqu'ici, notre chat peut avoir une très mauvaise santé (valeur négative) et avoir froid tout en continuant à jouer et à manger.
Pour faire un bon jeu, on doit ajouter un attribut supplémentaire, self.is_alive = True, et vérifier à chaque activité si le chat est toujours vivant avant d'exécuter cette activité. Si la valeur de l'attribut health (santé) passe en dessous de 0, on considérera que le chat est mort.
Peux-tu modifier le code pour en tenir compte ?
Dans notre exemple (qui n'est qu'une des multiples façons d'aborder cette situation), on ne va pas ajouter une nouvelle méthode, mais plutôt vérifier à chaque méthode appelée que le chat est toujours vivant. Le chat est considéré comme vivant s'il était vivant avant (pas de zombies !) et s'il est en assez bonne santé. Par exemple, dans la méthode sleep (dormir), on doit d'abord vérifier si le chat est vivant, puis continuer avec ce que la méthode est censée faire. Si le chat est mort, on ne devrait vraiment pas modifier le niveau de fatigue (sleepiness).
Voici à quoi la méthode est censée ressembler après la modification.
def sleeps(self):
# First, let's check if the cat is alive: the cat is alive if the cat was alive before and it's also healthy
self.is_alive = (self.is_alive and (self.health >= 0))
if self.is_alive:
self.sleepiness = 0
self.playfulness = 10
self.health += 1 if self.health < 10 else 0
self.hunger += 1 if self.hunger < 10 else 0
print(f"The cat {self.name} has slept!")
else:
print(f"Condolences, {self.name} is dead! If you want to play again, create a new Cat object.")
Bien, maintenant qu'on a vu comment modifier une des méthodes, vas-y et modifie toutes les méthodes. Écris ton propre code, puis clique sur le bouton pour comparer les options. Ce n'est pas grave d'avoir une solution différente, c'est normal que différentes personnes écrivent de différentes façons. Ce n'est pas grave d'avoir une solution différente, tant qu'elles fonctionnent et donnent les mêmes résultats (autrement dit, qu'elles répondent aux besoins) !
Click to reveal|||python||||||0|||Hide|||
class Cat():
# This is the constructor we previously saw
def __init__(self, name, sleepy, hungry, cold, playfulness, health):
## Let's add all the cat can be
self.name = name # example of variable filled during initialization
self.sleepiness = sleepy # This could be a boolean or a value from 0 to 9
self.hunger = hungry # This could be a boolean or a value from 0 to 9
self.cold = cold
self.playfulness = playfulness # Could also be thought as energy
self.health = health
self.is_alive = True
## Now let's add all the actions the cat can take
def sleeps(self):
# First, let's check if the cat is alive: the cat is alive if the cat was alive before and it's also healthy
self.is_alive = (self.is_alive and (self.health >= 0))
if self.is_alive:
self.sleepiness = 0
self.playfulness = 10
self.health += 1 if self.health < 10 else 0
self.hunger += 1 if self.hunger < 10 else 0
print(f"The cat {self.name} has slept!")
else:
print(f"Condolences, {self.name} is dead! If you want to play again, create a new Cat object.")
def plays_inside(self, mins_of_play = 30):
# First, let's check if the cat is alive: the cat is alive if the cat was alive before and it's also healthy
self.is_alive = (self.is_alive and (self.health >= 0))
if self.is_alive:
# The cat gets sleepier by each 10 minutes of play and loses all of its playfulness on the same hour
self.playfulness = (self.playfulness - int(mins_of_play /10)) if mins_of_play < 60 else 0 # normal use of ternary function
self.sleepiness = (self.sleepiness + int(mins_of_play /10)) if mins_of_play < 60 else 10
print(f"The cat {self.name} has played for {mins_of_play} minutes inside the house.")
else:
print(f"Condolences, {self.name} is dead! If you want to play again, create a new Cat object.")
def eats(self, spoons_of_tuna = 2):
# First, let's check if the cat is alive: the cat is alive if the cat was alive before and it's also healthy
self.is_alive = (self.is_alive and (self.health >= 0))
if self.is_alive:
# The cat loses the hunger after it eats 5 spoons of tuna, gets one more point more playful each 4 spoons of tuna
self.hunger = (self.hunger - spoons_of_tuna * 2) if spoons_of_tuna < 5 else 0
self.playfulness = (self.playfulness + int(spoons_of_tuna / 4)) if self.playfulness < 10 else 10
print(f"The cat {self.name} has eaten {spoons_of_tuna} spoons of tuna. Yum!")
else:
print(f"Condolences, {self.name} is dead! If you want to play again, create a new Cat object.")
Félicitations pour avoir amélioré le code ! Maintenant que tu as saisi la façon de coder les Class (classes), il ne te reste plus qu'à t'entraîner encore un peu !
💪 Défi
Utilise le code que tu as fait pour le défi de la quête précédente.
- Fais une copie du Colab de ta quête précédente.
- Après avoir validé les solutions aux quêtes précédentes proposées par certains de tes collègues, choisis 2 attributs et 2 méthodes de plus à ajouter à ton code. Ces nouveaux attributs et méthodes doivent être différents de ceux que tu as déjà écrits. Utilise des commentaires pour mettre en évidence les nouveaux ajouts.
- Ajoute quelques lignes de code supplémentaires au Code de test pour vérifier si les nouveaux attributs et méthodes fonctionnent correctement.
Critères de validation
- Le fichier lié est accessible à toute personne disposant du lien
- Toutes les missions ont été accomplies
Intro
So far in our journey through the Class topic, we learnt how to recognize them and how to build them with attributes and methods. All we are missing is a bit more pratice
Content
✅ In this quest you will practice, practice makes perfect!

Let's get better!
Before proceeding, please make sure all the topics covered in the previous quest are clear.
We will continue with the example of the Tamagochi cat we started in the previous quest. If you are not sure about which part of the code we will continue using, please find it here.
Schrödinger's Dilemma: is the cat alive?
Schrödinger's cat is an experiment that illustrates a paradox of quantum physics. The main question was "is the cat alive or dead?" and a definitive answer wasn't given. In our code is the same: so far, our cat can have very bad health (negative value) and cold and still be playing around and eating.
To make a good game, we need to add an additional attribute, self.is_alive = True, and check for every activity if the cat is still alive before performing the activity. If the health attribute's value goes below 0, I'll consider the cat dead.
Can you change the code in a way that accounts for that?
In our example - which is one of the multiple ways to address this situation - we are not going to add a new method but rather check during every method we call that the cat is still alive. The cat is considered alive if it was alive before (no zombies considered!) and if it is healthy enough. For example, in the sleep method, first we need to check if the cat is alive, then we need to continue with what the method is suppose to do. If the cat is dead, we really shouldn't change the sleepiness level.
This is how the method is suppose to look like after we change it.
def sleeps(self):
# First, let's check if the cat is alive: the cat is alive if the cat was alive before and it's also healthy
self.is_alive = (self.is_alive and (self.health >= 0))
if self.is_alive:
self.sleepiness = 0
self.playfulness = 10
self.health += 1 if self.health < 10 else 0
self.hunger += 1 if self.hunger < 10 else 0
print(f"The cat {self.name} has slept!")
else:
print(f"Condolences, {self.name} is dead! If you want to play again, create a new Cat object.")
Good, now that we have seen how to change one of the methods, go ahead and change all of the methods. Please make your own code, then click on the button to compare the options. It's OK to have a different solution, it's normal that different people write in a different way. It's OK to have a different solution, as long as they work and have the same results (A.K.A. match requirements)!
Click to reveal|||python||||||0|||Hide|||
class Cat():
# This is the constructor we previously saw
def __init__(self, name, sleepy, hungry, cold, playfulness, health):
## Let's add all the cat can be
self.name = name # example of variable filled during initialization
self.sleepiness = sleepy # This could be a boolean or a value from 0 to 9
self.hunger = hungry # This could be a boolean or a value from 0 to 9
self.cold = cold
self.playfulness = playfulness # Could also be thought as energy
self.health = health
self.is_alive = True
## Now let's add all the actions the cat can take
def sleeps(self):
# First, let's check if the cat is alive: the cat is alive if the cat was alive before and it's also healthy
self.is_alive = (self.is_alive and (self.health >= 0))
if self.is_alive:
self.sleepiness = 0
self.playfulness = 10
self.health += 1 if self.health < 10 else 0
self.hunger += 1 if self.hunger < 10 else 0
print(f"The cat {self.name} has slept!")
else:
print(f"Condolences, {self.name} is dead! If you want to play again, create a new Cat object.")
def plays_inside(self, mins_of_play = 30):
# First, let's check if the cat is alive: the cat is alive if the cat was alive before and it's also healthy
self.is_alive = (self.is_alive and (self.health >= 0))
if self.is_alive:
# The cat gets sleepier by each 10 minutes of play and loses all of its playfulness on the same hour
self.playfulness = (self.playfulness - int(mins_of_play /10)) if mins_of_play < 60 else 0 # normal use of ternary function
self.sleepiness = (self.sleepiness + int(mins_of_play /10)) if mins_of_play < 60 else 10
print(f"The cat {self.name} has played for {mins_of_play} minutes inside the house.")
else:
print(f"Condolences, {self.name} is dead! If you want to play again, create a new Cat object.")
def eats(self, spoons_of_tuna = 2):
# First, let's check if the cat is alive: the cat is alive if the cat was alive before and it's also healthy
self.is_alive = (self.is_alive and (self.health >= 0))
if self.is_alive:
# The cat loses the hunger after it eats 5 spoons of tuna, gets one more point more playful each 4 spoons of tuna
self.hunger = (self.hunger - spoons_of_tuna * 2) if spoons_of_tuna < 5 else 0
self.playfulness = (self.playfulness + int(spoons_of_tuna / 4)) if self.playfulness < 10 else 10
print(f"The cat {self.name} has eaten {spoons_of_tuna} spoons of tuna. Yum!")
else:
print(f"Condolences, {self.name} is dead! If you want to play again, create a new Cat object.")
Congratulation on improving the code! Now that you have grasped the way to code Classes, all it's left is to exercise some more!
💪 Challenge
Use the code you made for the previous quest's challenge.
- Make a copy of the Colab of your previous quest.
- After validating the solutions to the previous quests given by some of your colleagues, choose 2 more attributes and 2 more methods to add to your code. This new attributes and methods have to be different from the ones you have already written. Use comments to highlight the new additions.
- Add some more lines of code to the Test Code to check if the new attributes and methods work properly.
Validation criteria
- The linked file is available to anyone who has the link
- All the missions have been completed