将函数名称作为参数传递以定义泛型函数

时间:2015-05-12 03:32:33

标签: python function class

我有以下Python代码(在同一个类中定义了一些函数),如您所见。这2个函数基本相同,只是它们调用不同的函数:一个是调用self._init_module;另一个是呼叫self._config_module。所以我想要做的是定义一个通用的泛型函数,它可以传递函数名作为参数。我该如何实现呢?

# ULONG LAURAKIT_API LauraKitInitModule_1B(LAURA_HANDLE modHandle, ULONG *regAddr, ULONG *regData, UCHAR *size)
self._init_module = _lib.LauraKitInitModule_1B

# ULONG LAURAKIT_API LauraKitConfigRegister_1B
#                           (LAURA_HANDLE modHandle, OPERATION *ope, ULONG *regAddr, ULONG *regData, INT *size)
self._config_module = _lib.LauraKitConfigRegister_1B

def init_module(self, mod_h):
    """


    :param mod_h: module handler
    :return: operation, reg_addr, reg_data, size.value
    """
    mod_handle = ct.c_ulong(mod_h)

    Reg_Addr_Arr = ct.c_ulong * MAX_ARR_LEN
    Reg_Data_Arr = ct.c_ulong * MAX_ARR_LEN
    Reg_Oper_Seq = ct.c_ulong * MAX_ARR_LEN

    operation = Reg_Oper_Seq()
    reg_addr = Reg_Addr_Arr()
    reg_data = Reg_Data_Arr()

    size = ct.c_int(0)

    self._ok = self._init_module(mod_handle, operation, reg_addr, reg_data, ct.byref(size))

    return operation, reg_addr, reg_data, size.value

def config_module(self, mod_h):
    """
    Exactly the same function implementation as the init_module

    :param mod_h: module handler
    :return: operation, reg_addr, reg_data, size.value
    """
    mod_handle = ct.c_ulong(mod_h)

    Reg_Addr_Arr = ct.c_ulong * MAX_ARR_LEN
    Reg_Data_Arr = ct.c_ulong * MAX_ARR_LEN
    Reg_Oper_Seq = ct.c_ulong * MAX_ARR_LEN

    operation = Reg_Oper_Seq()
    reg_addr = Reg_Addr_Arr()
    reg_data = Reg_Data_Arr()

    size = ct.c_int(0)

    self._ok = self._config_module(mod_handle, operation, reg_addr, reg_data, ct.byref(size))

    return operation, reg_addr, reg_data, size.value

2 个答案:

答案 0 :(得分:3)

您可以直接传递函数,例如:

def process_module(self, mod_h, process_func):
    # Pre-processing...
    self._ok = process_func(mod_handle, operation, reg_addr, reg_data, ct.byref(size))
    return operation, reg_addr, reg_data, size.value

def init_module(self, mod_h):
    self.process_module(mod_h, self._init_module)

def config_module(self, mod_h):
    self.process_module(mod_h, self._config_module)

答案 1 :(得分:1)

def generic_caller(self, function_name, *args):
  if hasattr(self, function_name):
    function = getattr(self, function_name)
    function(*args)
  else:
    pass # Some error handling here

对于o.generic_caller('func', 1, 2, 3),它会完全按照o.func(1, 2, 3)

进行操作

实施例

>>> class Foo:
...   def generic_caller(self, function_name, *args):
...     if hasattr(self, function_name):
...       function = getattr(self, function_name)
...       function(*args)
...     else:
...       print ("There is no atribute called: " + function_name)
...   def dog(self):
...     print "hau"
...   def cat(self, times):
...     for _ in xrange(0, times):
...       print "mew"
... 
>>> bar = Foo()
>>> bar.generic_caller('dog')
hau
>>> bar.generic_caller('cat', 3)
mew
mew
mew