我正在設計一個模擬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
儘管我已經描述了自己的具體情況,但我誠摯地歡迎您進行一般性討論特殊方法的實施/使用是不好的做法。
提前,謝謝你的回答我的問題!
你描述的設計看起來很不錯。 – NPE 2013-03-02 20:42:34
這可能不適合堆棧溢出,因爲它要求進行「一般性討論」而不是針對特定問題的解決方案。 – ASGM 2013-03-02 20:46:50