2013-03-02 72 views
1

我正在設計一個模擬API的幾個部分(通過Windows DLL)接口的Python模塊。我想充分利用python,以便該庫既乾淨又易於使用。特殊方法(「魔術方法」)的實現/使用在python中是不好的做法?

在實現我自己的類與API的一部分對接,我發現自己想實現__getitem____setitem__作爲訪問器API的getValue()setValue()方法。它在仿真軟件中爲內部十六進制值提供了一個更清晰的接口,但這是一種不好的做法,或者可能不是pythonic?

下面是我想實現什麼樣的例子:

# Note that each word is identified by a unique integer and each has a 
# settable/retrievable hex value within the simulation software. 

class sim: 
    ... 
    ... 
    def __getitem__(self, key): 
     ''' check for valid key range (int)''' 
     ''' else throw exception ''' 
     val = simAPI.getValue(key) # returns the value of the word at the key in the 
            # software, None on failure 
     if val: 
      return val 
     '''else throw exception ''' 

    def __setitem__(self, key, value): 
     ''' check for valid key range and value (int, int)''' 
     ''' else throw exception ''' 

     if not simAPI.setValue(key, value): # sets the value of the word at the key in the 
     ''' throw exception'''    # software, None on failure 

    ... 
    ... 

這將使:

Word = sim() 

Word[20] = 0x0003 # set word 20 to hex value 0x0003 in the simulation software 

if Word[23] == 0x0005: # check if word 23 is equal to 0x0005 
    pass 

,也許有更多的發展,切片設置多個單詞:

Word[1:5] = 0x0004 # set words 1-5 to 0x0004 

儘管我已經描述了自己的具體情況,但我誠摯地歡迎您進行一般性討論特殊方法的實施/使用是不好的做法。

提前,謝謝你的回答我的問題!

+0

你描述的設計看起來很不錯。 – NPE 2013-03-02 20:42:34

+0

這可能不適合堆棧溢出,因爲它要求進行「一般性討論」而不是針對特定問題的解決方案。 – ASGM 2013-03-02 20:46:50

回答

2

這不一定是壞習慣。關於獲取和設置項目的事情是你只能爲他們做一個操作。也就是說,只有一種語法可以讓你用方括號做object[index]。所以最重要的是要確保你真的想用你定義的操作「用完」這個語法。

如果SimAPI這些getValue方法確實似乎是一個明顯的選擇 - 那就是,如果getValue真正得到價值,而不僅僅是一個 - 它似乎罰款。你想要避免的是選擇一個相對隨機或非特殊的操作,並通過__getitem__訪問它來賦予它特殊的狀態。