Search code examples
pythonstringclassformatkeyerror

Python .format() KeyError when using class.__dict__


Basically I have a class defined and I'm trying to display its attributes in a print statement EDIT:

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))

Am I doing something wrong? I'm just trying to find a more efficient way to display attributes of a class rather than doing...

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

Any ideas?


Solution

  • You've forgotten to use self. in your Player.__init__ function, and you've forgotten to use ** in your call to str.format.

    Here is working code:

    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__))