Reputation: 3
I got this task at school: "Complete the Animal class to have and a class variable animals (list) and two instance variables, name (str) and number (int). You need to implement init and str methods" This what I did:
class Animal:
animals = []
number = 0
def __init__(self, name):
self.name = name
Animal.number =+1
def __str__(self):
return f"{Animal.number}. {self.name.capitalize()}"
The following is the test that I should fulfill:
Animal.animals.clear()
dog = Animal('dog')
assert dog.name == 'dog'
assert dog.number == 1
assert str(dog) == '1. Dog'
cat = Animal('cat')
assert cat.name == 'cat'
assert cat.number == 2
assert str(cat) == '2. Cat'
I do not understand how to use the list in this case (also how to fill it) and how to keep the number updated. I am a beginner so please keep a simple language, thank you so much.
Upvotes: 0
Views: 152
Reputation: 6206
In short:
x = +1
==> x = 1
x += 1
==> x = x + 1
So change Animal.number = +1
to Animal.number += 1
.
Upvotes: 0
Reputation: 435
Simply add to the animals list when a new animal instance is created, inside the init.
class Animal:
animals = []
number = 0
def __init__(self, name):
self.name = name
Animal.animals.append(name)
Animal.number += 1 # '+=' not '=+'
def __str__(self):
return f"{Animal.number}. {self.name.capitalize()}"
If you don't want the same animal in the list twice you can do:
if name not in Animal.animals:
Animal.animals.append(name)
Upvotes: 1