我在我的顶级王牌风格游戏上取得了进展,并希望能够将我的超级英雄级别创建的实例分成2个套牌。如果我只是使用普通列表或元组创建套牌列表,则下面的代码可以工作但我无法弄清楚为什么它在使用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)
然而,当我在我的程序中使用它时,它会抛出错误消息,例如< main .Superhero对象,位于0x020FC510>
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)
答案 0 :(得分:4)
这不是错误,如果没有指定其他表示方式,它就是表示对象的方式。因此,要解决此问题,您应该实现__repr__
类的Superhero
方法。像这样:
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。