Yahtzee game, __str__ not working

时间:2016-07-11 20:48:07

标签: python

I realize I've been pretty much spamming this forum lately, I'm just trying to break my problems down since I'm supposed to create a yahtzee game for assignment. My code is currently looking like this:

class Player:
    def __init__(self,name):
        self.name=name
        self.lista={"ones":0,"twos":0,"threes":0, "fours":0,"fives":0,"sixs":0,"abovesum":0,"bonus":0,"onepair":0,"twopair":0,"threepair":0,"fourpair":0,"smalladder":0,"bigladder":0,"house":0,"chance":0,"yatzy":0,"totalsum":0}
        self.spelarlista=[]

    def __str__(self):
        return self.name

    def welcome(self):
        print("Welcome to the yahtzee game!")
        players = int(input("How many players: "))
        rounds=0
        while not players==rounds:
            player=input("What is your name?: ")
            rounds=rounds+1
            self.spelarlista.append(Player(player))
            print(self.spelarlista)


def main():
    play=Player("Joakim")
    play.welcome()
    for key in ["names","ones","twos","threes","fours","fives","sixs","abovesum","bonus","onepair","twopair","threepair","fourpair","smalladder","bigladder","house","chance","yatzy","totalsum"]:
        print("%-20s"%key)


main()

My goal is that its gonna look something like this: https://gyazo.com/26f997ed05c92898d93adaf0af57d024

If you look at my method "welcome", I do want to print my self.spelarlista, just to see how its gonna look, but all I get is "Player object at 0x7fac824....", I realize something is wrong with my str, how should I change it?

2 个答案:

答案 0 :(得分:1)

When you print a list of objects python doesn't call the objects __str__ method but the container list. If you want to print them all you can call the __str__ method by applying the built-in function str() on them using map() or a list comprehension and join them with str.join() method.

print(' '.join(map(str, self.spelarlista)))

Or as another alternative approach you can define a __repr__ attribute for your objects, which returns the official string representation of an object:

>>> class A:
...    def __init__(self):
...        pass
...    def __repr__(self):
...       return 'a'
... 
>>> l = [A()]
>>> 
>>> print l
[a]

答案 1 :(得分:1)

If you are getting Player object at 0x7fac824 or anything similar, it seems that you are calling the repr on the object (indirectly), which in turn calls the object's __repr__ method.

class Player:
    # ...

    def __repr__(self):
        return self.name

    # ...

Since there is no __str__ method defined, __str__ will also default to calling __repr__.

__repr__ returns a string representation of the object (usually one that can be converted back to the object, but that's just a convention) which is what you need.