1

I'm designing a python module that interfaces with several parts of a simulation API (via windows dll). I would like to make full use of python so that the library is both clean and simple to use.

When implementing my own class to interface with a part of the API, I found myself wanting to implement __getitem__ and __setitem__ as accessors to the API's getValue() and setValue() methods. It provides a cleaner interface to the internal hex values within the simulation software, but is this bad practice or perhaps not pythonic?

Below is an example of what I would like to implement:

# 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

    ...
    ...

This would allow for:

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

and maybe with more development, slicing to set multiple words:

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

Although I have described my specific case, I sincerely welcome a general discussion on what implementations/uses of special methods are bad practice.

In advance, thank you for your time in answering my question!

4

1 に答える 1

2

それは必ずしも悪い習慣ではありません。アイテムの取得と設定については、1つの操作しか取得できません。つまり、object[index]角かっこを使用できる構文は1つだけです。したがって、重要なことは、定義している操作でその構文を本当に「使い切る」ことを確認することです。

SimAPIでこれらのgetValueメソッドが実際に明白な選択のように見える場合、つまりgetValue値だけでなく実際に値を取得する場合は、問題ないように見えます。避けたいのは、比較的ランダムな操作または特別でない操作を選択し、それにアクセスすることで特別なステータスを与えることです。__getitem__

于 2013-03-02T20:45:57.820 に答える