1

我正在设计一个 python 模块,它与模拟 API 的几个部分(通过 windows dll)接口。我想充分利用python,使库既干净又易于使用。

在实现我自己的类以与 API 的一部分接口时,我发现自己想要实现__getitem____setitem__作为 APIgetValue()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

虽然我已经描述了我的具体案例,但我真诚地欢迎就特殊方法的哪些实现/使用是不好的做法进行一般性讨论。

在此先感谢您抽出宝贵时间回答我的问题!

4

1 回答 1

2

这不一定是坏习惯。关于获取和设置项目的事情是您只能为它们进行一次操作。也就是说,只有一种语法可以让您object[index]使用方括号。所以主要的事情是确保你真的想用你定义的操作“用完”那个语法。

如果在 SimAPI 中这些getValue方法确实看起来是一个显而易见的选择——也就是说,如果getValue真的得到值而不仅仅是一个值——那似乎很好。您要避免的是选择一个相对随机或非特殊的操作,并通过__getitem__访问它来赋予它特殊的状态。

于 2013-03-02T20:45:57.820 回答