python 3.10.2-在类中打印对象的列表
开始学习对象并在打印作为方法方面存在问题。
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(Animal)
替换 循环 main()。
尝试为__ 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 __。动物对象,请访问0x000001521C48AD40>,
。
def __repr__(self):
return self.__str__()
________________ typeError:只能连接元组(不是“ str”)到元组
,在这里我的想法如何修复它结束。
Started learning objects and have problem with printing 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")
I would want to replace for
loop in main()
by just a simple print(animals)
.
Tried as __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
but it's generating me following error:[<__main__.Animal object at 0x000001521C48AD40>, <__main__.Animal object at 0x000001521C48AC80>]
Found and answer with __repr()__
:
def __repr__(self):
return self.__str__()
which says:TypeError: can only concatenate tuple (not "str") to tuple
and here my ideas how to fix it ends.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这条线结束时有一个逗号,
使它看起来像
rep
是一个元组。There's a comma at the end of this line
making it seem like
rep
is a tuple.