2014-06-11 66 views
0

我的程序未能取消激發我的數據,其中pickle.load(f)與pickle.dump(object,f)不匹配。 我的問題是我在哪裏用下面的代碼去錯了,因爲我已經嘗試了各種 文件模式上面下面我的代碼列出的相應錯誤:未挑選的對象與原始對象不匹配

F =開放(家+「/.GMouseCfg」, 'AB +')

出:它們是不同

F =開放(家+ '/.GMouseCfg','ab+',編碼= 'UTF-8')

ValueError異常:二進制模式並不需要的編碼參數

F =開放(家+ '/.GMouseCfg','a+')

類型錯誤:必須海峽,而不是字節

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文檔的泡菜和文件IO但我無法辨別很多,爲什麼有我原來的對象和拆封一個

之間的差異

回答

2

酸洗和拆除後,顯然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 
    ... 
+0

這解決了這個問題。我最深的歉意,我沒有意識到,eq操作員將需要超載來檢查平等。那麼,這兩個命令和命令2都具有相同的數據和結構,我甚至需要測試它。我幾個星期前開始學習python,但它應該點擊,因爲我重載了等於運營商在c + +和c# – meschael