0

我希望包装一个 C 库以在 python 中使用。我还希望使用测试驱动开发来实现我的课程。这是我到目前为止编写的两个类及其接口。我需要包装一大堆像这样的类。

class FunctionWrapperForOurLibrary:
    def __init__():
        pass

    def __call__():
        pass

class OurOpener(FunctionWrapperForOurLibrary):
    def __init__(self, our_library):
        self.our_library = our_library
        our_library.OurOpen.argtypes = [c_char_p, c_char_p]
        our_library.OurOpen.restype = OUR_ERROR

    def __call__(self, admin_path, company_path):
        status = self.our_library.OurOpen(admin_path, company_path)
        if status.lRc:
            raise Exception("Unable to connect to database due to this error: "+str(status.lRc))

class OurDataCreator(FunctionWrapperForOurLibrary):
    def __init__(self, our):
        self.our_library = our_library
        our_library.OurCreateData.argtypes = [c_int]
        our_library.OurCreateData.restype = POINTER(OUR_DATA)

    def __call__(self, our_structure_type):
        data = self.our_library.OurCreateData(our_structure_type)
        return data

第一个问题,我是否通过包含接口类来提高可读性?我意识到它不需要。我的对象和类名呢?关于如何使这些更清晰的任何建议?

其次,我如何编写一个包含这些函子的类?一个可单元测试的类?

我能想到的最好的方法是:

class Our:
    def __init__(self, our_open, our_data_create, ...):
        self.opener = our_open
        self.data_create = our_data_create

our_open = OurOpener(our_library)
our_data_create = OurDataCreator(our_library)
our = Our(our_open, our_data_create)

但我将有大量函子传递给类构造函数。

这样做有什么更好的吗?

更新:

class Our:
    def __init__(self, our_library):
        self.our_library = our_library
        our_library.OurOpen.argtypes = [c_char_p, c_char_p]
        our_library.OurOpen.restype = OUR_ERROR
        our_library.OurCreateData.argtypes = [c_int]
        our_library.OurCreateData.restype = POINTER(OUR_DATA)

    def open(self, admin_path, company_path):
        status = self.our_library.OurOpen(admin_path, company_path)
        if status.lRc:
            raise Exception("Unable to connect to database due to this error: "+str(status.lRc))

    def create_data(self, our_structure_type):
        return self.our_library.OurCreateData(our_structure_type)
4

0 回答 0