Python .format() 使用 class.__dict__ 时出现 KeyError
Python .format() KeyError when using class.__dict__
基本上我有一个 class 定义,我试图在打印语句中显示它的属性编辑:
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))
我是不是做错了什么?我只是想找到一种更有效的方法来显示 class 的属性,而不是做...
print(character.name + ': Weight: ' + character.weight + ' Age: ' +
character.age + '...')
有什么想法吗?
您忘记在 Player.__init__
函数中使用 self.
,并且您忘记在 str.format
.[=15 的调用中使用 **
=]
这是工作代码:
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__))
基本上我有一个 class 定义,我试图在打印语句中显示它的属性编辑:
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))
我是不是做错了什么?我只是想找到一种更有效的方法来显示 class 的属性,而不是做...
print(character.name + ': Weight: ' + character.weight + ' Age: ' +
character.age + '...')
有什么想法吗?
您忘记在 Player.__init__
函数中使用 self.
,并且您忘记在 str.format
.[=15 的调用中使用 **
=]
这是工作代码:
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__))