【问题标题】:Unpickled object does not match original未腌制的对象与原始对象不匹配
【发布时间】:2014-08-02 00:18:16
【问题描述】:

我的程序无法解开我的数据,其中 pickle.load(f) 与 pickle.dump(object,f) 不匹配。 我的问题是以下代码哪里出错了,因为我已经尝试了各种 文件模式与下面我的代码上方列出的相应错误:

f = open(home + '/.GMouseCfg','ab+')

out:它们是不同的

f = open(home + '/.GMouseCfg','ab+', encoding='utf-8')

ValueError:二进制模式不接受编码参数

f = open(home + '/.GMouseCfg','a+')

TypeError: 必须是 str,而不是 bytes

import abc, pprint
from evdev import ecodes as e
from os.path import expanduser

try:
    import cPickle as pickle
except:
    import pickle


class Command(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def set(self, data):
        """set data used by individual commands"""
        return

    @abc.abstractmethod
    def run(self):
        """implement own method of executing data of said command"""
        return

class KeyCommand(Command):
    def __init__(self, data):
        self.data = data
    def set(data):
        self.data = data
    def run(self):
        pass
    def __str__(self):
        return data

class SystemCommand(Command):
    def __init__(self, data):
        self.data = data
    def set(data):
        self.data = data
    def run(self):
        pass
    def __str__(self):
        return data

if __name__ == '__main__':
    ids = [2,3,4,5,6,7,8,9,10,11,12]
    home = expanduser('~')
    f = open(home + '/.GMouseCfg','a+')
    f.seek(0)

    commands = list()
    commands.append(KeyCommand({3:[e.KEY_RIGHTCTRL,e.KEY_P]}))
    commands.append(SystemCommand({5:['gedit','./helloworld.txt']}))
    pickle.dump(commands,f)
    f.seek(0)
    commands2 = pickle.load(f)
    if commands == commands2:
        print('They are the same')
    else:
        print('They are different')

我已经阅读了大量有关泡菜和文件 io 的 python 文档,但无法辨别为什么我的原始对象和未腌制的对象之间存在差异

【问题讨论】:

    标签: python-3.x file-io pickle


    【解决方案1】:

    酸洗和解酸之后,显然commandcommand2 永远不会是同一个对象了。

    这意味着commands == commands2 将始终返回False,除非您为您的类实现comparision,例如:

    class KeyCommand(Command):
        ...
        def __eq__(self, other):
            return self.data == other.data
        def __ne__(self, other):
            return self.data != other.data
        ...
    
    class SystemCommand(Command):
        ...
        def __eq__(self, other):
            return self.data == other.data
        def __ne__(self, other):
            return self.data != other.data
        ...
    

    【讨论】:

    • 这解决了问题。我深表歉意,我没有意识到需要重载 eq 运算符来检查是否相等。那么命令和命令2是否具有相同的数据和结构,我什至需要对此进行测试。几周前我开始学习 python,但它应该已经成功了,因为我在 c++ 和 c# 中重载了等于运算符
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 2016-03-27
    • 2017-10-08
    • 2018-10-30
    • 2022-07-16
    • 2018-12-09
    • 2021-08-18
    相关资源
    最近更新 更多