【问题标题】:How would one go about printing/saving a dictionary that uses Class Instances?如何打印/保存使用类实例的字典?
【发布时间】:2021-08-02 10:01:00
【问题描述】:

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

{'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, '3/6/9/18', 'Slugga', 'Choppa')}

我尝试了诸如使用 print(repr(entities)) 之类的方法,但似乎都失败了。如果有任何见解,我将不胜感激,我将在下面发布更长的代码 sn-p 以提供更多上下文。

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', 10, '3/6/9/18', 'Lasgun', 'Knife'),
    'orkboy': Entity('Ork Boy', 12, '3/6/9/18', 'Slugga', 'Choppa')
}

print(entities)
print(repr(entities)

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

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

【问题讨论】:

  • 可以用泡菜吗?

标签: python class dictionary save instance-variables


【解决方案1】:

覆盖类的__str____repr__ 方法。

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

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

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

【讨论】:

    【解决方案2】:

    您可以将字典转换为字符串表示形式。在类中添加一个__str__(self) 方法。然后,使用 Dictionary 理解和字典的 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: {}, {}, {}, {}'.format(self.name, self.wounds, self.movement, self.weapon, 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, 3/6/9/18, Slugga, Choppa'}
    

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 2014-10-19
      相关资源
      最近更新 更多