pasta1020 pasta1020 - 26 days ago 6
Python Question

Printing a list from a class in Python

Simplified code below - creates an animal, places it inside a zoo. I want to print the list of animals within the zoo. Going round in circles with this! Any help appreciated.

class Animal(object):

def __init__(self, name):
self.name = name

class Zoo(object):

def __init__(self):
self.animals = []

def __str__(self):
rep = ", ".join(self.animals)
return rep

def add(self, name):
self.animals.append(Animal(name))

def main():

while True:
zoo = Zoo()
animal = input("add an animal: ")
zoo.add(animal)
print(zoo)

main()

Answer

The added __repr__ Method to the Animal returns us the name.

The zoo = Zoo() has to be outside of the loop, this makes sure that we do not create a new zoo with every iteration.

Then we print the list (zoo.animals).

class Animal(object):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return self.name



class Zoo(object):
    def __init__(self):
        self.animals = []
    def __str__(self):
        rep = ", ".join(self.animals)
        return rep
    def add(self, name):
        self.animals.append(Animal(name))



def main():
    zoo = Zoo()
    while True:
        animal = input("add an animal: ")
        zoo.add(animal)
        print(zoo.animals)


main()
Comments