简体   繁体   中英

Classes in Python: __str__ method and list

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.

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)

In short:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM