如何打印/保存使用类实例的字典?

问题描述

我今天尝试了十几种不同的方法解决这个问题,但遗憾的是到目前为止还没有骰子。截至目前,我目前正在尝试保存字典,但由于键使用的值来自类,因此遇到了不幸的副作用。当我按原样打印/保存这本词典时,我收到以下输出

{'imperialguard': ma​​in.Entity object at 0x00000180CC2E1FD0>,'orkboy':ma​​in.Entity 对象在 0x00000180CC2E1FA0>}

可以想象,这些信息作为字典并不是很有用。我试图打印/保存的内容可以在下面收集。

entities = {
'imperialguard': Entity('Imperial Guardsman',10,'3/6/9/18','Lasgun','Knife'),'orkboy': Entity('Ork Boy',12,'Slugga','Choppa')}

我尝试过使用 print(repr(entities)) 之类的方法,但似乎一切都不尽如人意。我将不胜感激任何见解,我将在下面发布更长的代码片段以提供更多上下文。

class Entity:

    woundChange = 0

    def __init__(self,name,wounds,movement,weapon,melee):
        self.name = name
        self.wounds = wounds
        self.movement = movement
        self.weapon = weapon
        self.melee = melee

    def array(self):
        return '{}; HP: {},{},{}'.format(self.name,self.wounds,self.movement,self.weapon,self.melee)


entities = {
    'imperialguard': Entity('Imperial Guardsman','Choppa')
}

print(entities)
print(repr(entities)

z = open("entities.txt","w")
z.write(str(entities))
z.close()

祝您一切顺利,感谢您的阅读。

解决方法

您可以将字典转换为字符串表示形式。向类添加一个 __str__(self) 方法。然后,使用字典理解和字典的 items() 方法转换字典,如下所示:

class Entity:

    woundChange = 0

    def __init__(self,name,wounds,movement,weapon,melee):
        self.name = name
        self.wounds = wounds
        self.movement = movement
        self.weapon = weapon
        self.melee = melee

    def array(self):
        return '{}; HP: {},{},{}'.format(self.name,self.wounds,self.movement,self.weapon,self.melee)

    def __str__(self):
        return '{}; HP: {},self.melee)

str_dict = {k: str(v) for k,v in entities.items()}

测试:

print(str_dict)

z = open("entities.txt","w")
z.write(str(str_dict))
z.close()

结果:

{'imperialguard': 'Imperial Guardsman; HP: 10,3/6/9/18,Lasgun,Knife','orkboy': 'Ork Boy; HP: 12,Slugga,Choppa'}
,

覆盖类的 __str____repr__ 方法。

Entity从对象类继承了一些内置函数。 __str__ 是一种方法,用于指示当对象被视为字符串时要显示的内容。类似地,__repr__ 方法指示当对象传递给文件处理程序(可以是 stdout、stderr 或文件)时显示的内容。因此,要获得人类友好的输出,请覆盖该类的 __str____repr__ 方法。

class Entity:
    # ...
    # ...
    def __str__(self):
        return self.array()

    def __repr__(self):
        return self.array()