我希望包装一个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)