使用class .__ dict__时的Python .format()KeyError

时间:2015-10-29 21:49:05

标签: python string class format keyerror

基本上我定义了一个类,我试图在print语句中显示它的属性编辑:

class Player(object):
    """ Default Class for the player """
    def __init__(self, name):
        self.name = name
        self.class_type = '[CLASS]'
        self.level = 1
        self.health = 10
        self.maxhealth = self.level * 10
        self.attack = 0
        self.defence = 0
        self.experience = 0
        self.weapon = ''
        self.shield = ''
        self.player_y = 9
        self.player_x = 39

print('LV: {level} EXP: {exp} HP: {health}/' +
      '{maxhealth}'.format(**char))

我做错了吗?我只是想找到一种更有效的方式来显示类的属性,而不是做...

print(character.name + ': Weight: ' + character.weight + ' Age: ' +
      character.age + '...')

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您已忘记在self.功能中使用Player.__init__,而且您在**的通话中忘记使用str.format。< / p>

这是工作代码:

class Player(object):
    def __init__(self, name):
        self.name = name
        self.age = 125
        self.height = 72
        self.weight = 154
        self.sex = 'Male'

character = Player('NAME')

print('{name} {height} {weight} {sex}'.format(**character.__dict__))