Python 3.10.2 - 打印 类 中的对象列表作为方法

Python 3.10.2 - printing a list for objects in classes as method

开始学习对象,但打印为方法时遇到问题。

import random

class Animal(object):
    
    def __init__(self, race, name, hunger, boredom):
        race = input("Animals race: ")
        name = input("Animals name: ")
        hunger = random.randrange(0, 6)
        boredom = random.randrange(0, 6)
        self.race = race
        self.name = name
        self.hunger = hunger
        self.boredom = boredom
        
def main():
    animals = []
    animals.append(Animal(None, None, None, None))
    animals.append(Animal(None, None, None, None))

    for i in animals:
        print("\n", i.race, "named", i.name, "\n\n",
              "Status:\n",
              "Hunger:", i.hunger, "\n",
              "Boredom:", i.boredom, "\n")

main()

input("To exit press enter")

我想用一个简单的 print(animals).

替换 main() 中的 for 循环

尝试过 __str__()

    def __str__(self):
        rep = "\n" + self.race + "named" + self.name +"\n\n",
        rep += "Status:\n"
        rep += "Hunger:" + str(self.hunger) + "\n"
        rep += "Boredom:" + str(self.boredom) + "\n"
        return rep

但它给我带来了以下错误: [<__main__.Animal object at 0x000001521C48AD40>, <__main__.Animal object at 0x000001521C48AC80>]

找到并回答__repr()__

    def __repr__(self):
        return self.__str__()

它说: TypeError: can only concatenate tuple (not "str") to tuple

我的解决方法到此结束。

这一行末尾有一个逗号

    rep = "\n" + self.race + "named" + self.name +"\n\n",

让它看起来像 rep 是一个元组。