如何使用__str__更改对象属性的显示方式?

时间:2019-02-05 02:08:42

标签: python string class

我希望玩家的筹码显示为$ xxx,但要保持筹码为整数。我尝试了下面的代码,但是 str 部分只是灰色。我在做什么错了?

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)

1 个答案:

答案 0 :(得分:1)

您需要做的是取消__str__函数的缩进,它将正常工作:

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)