0

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.

1
  • Since this is a coding-specific question, it is imperative that you state exactly which version of Python you are using. Commented Jun 4, 2020 at 8:29

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! it was exactly what I needed :D
0

In short:

  • x = +1 ==> x = 1
  • x += 1 ==> x = x + 1

So change Animal.number = +1 to Animal.number += 1.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.