"it's not the same object as" 尝试序列化对象时出错

"it's not the same object as" error when trying to serialize an object

我一直在尝试制作一个基于文本的游戏,并认为我可能需要一个保存系统。这是我到目前为止所做的:

class Player:
    def __init__(self, health, defence, att, inventory, money, name):
        self.health = health
        self.defence = defence
        self.att = att
        self.inventory = inventory
        #set the inventory as a list and add items to it
        self.money = money
    def strike(self, enem):
        ...
    def addtoinv(self, item):
        ...

这是我的代码片段,它使播放器 class。

Player = Player(20, 5, 0, [], 0)

我在这里制作玩家对象。

f = open("save_file.dat", "wb+")
pickle.dump([Player], f)

这就是问题发生的地方。我正在尝试序列化该对象并将其保存到文件中,但它却抛出了这个错误:

_pickle.PicklingError: Can't pickle <class '__main__.Player'>: it's not the same object as __main__.Player

您正在用变量 Player 覆盖 class Player。这是将 Player 重新分配给 class 的实例而不是 class 本身。

您需要做的就是将您的变量重命名为其他名称

p = Player(20, 5, 0, [], 0)