帮助——Python中的函数指针

2024-05-12 22:29:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我的计划理念:

我有一本字典:

options = { 'string' : select_fun(function pointer),
'float' : select_fun(function pointer),
'double' : select_fun(function pointer)
}

无论哪种类型都会调用单个函数select_fun(function pointer)。 在select_fun(function pointer)中,我将拥有float、double等的diff函数。

根据函数指针,将调用指定的函数。

我不知道我的编程知识是好是坏,但我仍然需要帮助。


Tags: 函数类型string字典difffunctionfloatselect
3条回答

您可以使用^{} built-in function来检测函数的类型。

例如,如果要检查某个名称是否包含字符串数据,可以执行以下操作:

if type(this_is_string) == type('some random string'):
    # this_is_string is indeed a string

所以在你的情况下,你可以这样做:

options = { 'some string'     : string_function,
            (float)(123.456)  : float_function,
            (int)(123)        : int_function
          }

def call_option(arg):

    # loop through the dictionary
    for (k, v) in options.iteritems():

        # if found matching type...
        if type(k) == type(arg):

            # call the matching function
            func = option[k]
            func(arg)

然后你可以这样使用它:

call_option('123')       # string_function gets called
call_option(123.456)     # float_function gets called
call_option(123)         # int_function gets called

我附近没有python解释器,也没有用python编写太多程序,所以可能会有一些错误,但您应该明白这一点。


编辑:根据@Adam的建议,您可以直接检查内置的类型常量,因此更好的方法是:

from types import *

options = { types.StringType  : string_function,
            types.FloatType   : float_function,
            types.IntType     : int_function,
            types.LongType    : long_function
          }

def call_option(arg):
    for (k, v) in options.iteritems():

        # check if arg is of type k
        if type(arg) == k:

            # call the matching function
            func  = options[k]
            func(arg)

由于键本身与type()函数的值相当,您可以这样做:

def call_option(arg):
    func = options[type(arg)]
    func(arg)

这是更优雅的:-)保存一些错误检查。


编辑:对于ctypes支持,经过一些修改后,我发现ctypes[type_name_here]实际上是作为类实现的。所以这个方法仍然有效,您只需要使用ctypes.c_xxx类型类。

options = { ctypes.c_long     : c_long_processor,
            ctypes.c_ulong    : c_unsigned_long_processor,
            types.StringType  : python_string_procssor
          }

call_option = lambda x: options[type(x)](x)

看看你的例子,在我看来,这是一个直接翻译成Python的C过程。

因此,我认为可能存在一些设计问题,因为在Python中,通常不关心对象的类型,而只关心可以发送给它的消息。

当然,这种方法有很多例外,但在这种情况下,我还是会尝试封装一些多态性;例如

class StringSomething(object):
  data = None
  def data_function(self):
     string_function_pointer(self.data)

class FloatSomething(object):
  data = None
  def data_function(self):
     float_function_pointer(self.data)

等等

同样,所有这些都是假设您正在从过程语言转换为python;如果不是这样,请放弃我的答案:-)

你能更具体地说明你想做什么吗?在Python中,您不必做任何特殊的事情来获取函数指针——您可以像普通对象一样传递函数:

def plus_1(x):
    return x + 1

def minus_1(x):
    return x - 1

func_map = {'+' : plus_1, '-' : minus_1}

func_map['+'](3)  # returns plus_1(3) ==> 4
func_map['-'](3)  # returns minus_1(3) ==> 2

相关问题 更多 >