基本上我定义了一个类,我试图在打印语句中显示它的属性编辑:
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 + '...')
有什么想法吗?
最佳答案
您忘记在 Player.__init__
函数中使用 self.
,并且忘记在您的 **
中使用 **
调用str.format
。
这是工作代码:
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__))
关于Python .format() 使用 class.__dict__ 时出现 KeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33425222/