在python中从类实例创建列表

2024-05-16 01:13:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我在我的顶级王牌风格的游戏上取得了进展,希望能够将我的超级英雄类创建的实例分为两组。如果我只是使用普通列表或元组创建甲板列表,那么下面的代码可以工作,但是我不明白为什么在使用Superhero类的实例时会抛出错误消息。我相信这很简单,但我想不出来,请帮忙。你知道吗

所以这是独立的。。。你知道吗

from random import shuffle

hulk = ["Hulk", 10, 10, 1, 1, 7, 10]
thor = ["Thor", 1, 8, 8, 7, 8, 9]
ironMan = ["Iron Man", 9, 9, 10, 8, 9, 8]
blackWidow = ["Black Widow", 6, 7, 8, 10, 7, 4]
spiderman = ["Spiderman", 6, 9, 10, 9, 9, 9]
captainAmerica = ["Captain America", 5, 8, 9, 10, 7, 6]

deck = [thor, hulk, ironMan, blackWidow, spiderman, captainAmerica]


shuffle (deck)

half = int(len(deck)/2)
p1 = (deck[0:half])
cpu = (deck[half:])


print (p1)
print (cpu)

但是,在我的程序中使用时,它不会抛出错误消息,如0x020FC510处的<;main.Superhero对象>

import random

from random import shuffle

class Superhero (object):

def __init__(self, name, beast_rating, power, intelligence, specialpower, fightingskills, speed):
    self.name = name
    self.beast_rating = beast_rating
    self.power = power
    self.intelligence = intelligence
    self.specialpower = specialpower
    self.fightingskills = fightingskills
    self.speed = speed


hulk = Superhero("Hulk", 10, 10, 1, 1, 7, 10)
thor = Superhero("Thor", 1, 8, 8, 7, 8, 9)
ironMan = Superhero("Iron Man", 9, 9, 10, 8, 9, 8)
blackWidow = Superhero("Black Widow", 6, 7, 8, 10, 7, 4)
spiderman = Superhero("Spiderman", 6, 9, 10, 9, 9, 9)
captainAmerica = Superhero("Captain America", 5, 8, 9, 10, 7, 6)


deck = [thor, hulk, ironMan, blackWidow, spiderman, captainAmerica]

shuffle (deck)

half = int(len(deck)/2)
p1 = (deck[0:half])
cpu = (deck[half:])

print (p1)
print (cpu)

Tags: selfrandomcputhorprintdeckshufflep1
1条回答
网友
1楼 · 发布于 2024-05-16 01:13:37

这不是一个错误,它只是表示对象的方式,如果没有指定其他表示方式。因此,要解决这个问题,应该实现Superhero类的__repr__方法。像这样:

class Superhero (object):

    ....

    def __repr__(self):
        return "Superhero({}, {}, {}, {}, {}, {}, {})".format(self.name, 
                self.beast_rating, self.power, self.intelligence, 
                self.specialpower, self.fightingskills, self.speed)

然后它将列表打印为[Superhero(Hulk, 10, 10, 1, 1, 7, 10), Superhero(Iron Man, 9, 9, 10, 8, 9, 8), Superhero(Black Widow, 6, 7, 8, 10, 7, 4)]。你知道吗

有关__repr__和相关__str__方法的详细说明,请参见this answer。你知道吗

相关问题 更多 >