简体   繁体   中英

creating lists from class instances in python

I am making progress on my top trumps style game and want to be able to separate the instances created from my Superhero class into 2 decks. The code below works if I am just creating the deck list using normal lists or tuples but I can't figure out why it throws up an error message when using the instances from the Superhero class. I am sure it is something simple but I can't figure it out, please help.

So this works on its own...

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)

However when used in my program it does not, throws out error messages like < main .Superhero object at 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)

That is not an error, it is just the way objects are represented if no other way of representation is specified. Thus, to fix the problem, you should implement the __repr__ method of your Superhero class. Something like this:

class Superhero (object):

    ....

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

It will then print the lists as [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)] .

See this answer for a great explanation of __repr__ and the related __str__ method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM