简体   繁体   中英

How can I use __str__ to change how an attribute of my objects shows up?

I want the chips my player has to show up as $xxx, but to keep the chips as an int. I tried the code below, but the str part is just grey. What am I doing wrong?

class Player:
    def __init__(self, name, gender, taunt, aggression, hand, chips):
        self.name = name
        self.gender = gender
        self.taunt = taunt
        self.aggression = aggression
        self.hand = hand
        self.chips = chips

        def __str__(self):
            return "${0}".format(self.chips)

What you need to do is unindent the __str__ function and it will work as normal:

class Player:
    def __init__(self, name, gender, taunt, aggression, hand, chips):
        self.name = name
        self.gender = gender
        self.taunt = taunt
        self.aggression = aggression
        self.hand = hand
        self.chips = chips

    # Note the outdent of the function

    def __str__(self):
        return "${0}".format(self.chips)

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