我的程序无法解开我的数据,其中pickle.load(f)与pickle.dump(object,f)不匹配。 我的问题是我在下面的代码中出错了,因为我已经尝试过各种各样的代码 我的代码上面列出了相应错误的文件模式:
f = open(主页+' /。GMouseCfg',' ab +')
out:他们是不同的
f = open(主页+' /。GMouseCfg',' ab +',encoding =' utf-8')
ValueError:二进制模式没有采用编码参数
f = open(主页+' /。GMouseCfg',' a +')
TypeError:必须是str,而不是字节
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')
我已经在python docs上做了很多关于pickle和file io的阅读,但是我无法辨别为什么我的原始对象和unpickled之间存在差异
答案 0 :(得分:2)
在酸洗和去除斑点后,显然command
和command2
永远不会是同一个对象。
这意味着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
...