use*_*646 3 python pointers function
我对程序的想法:
我有一本字典:
options = { 'string' : select_fun(function pointer),
'float' : select_fun(function pointer),
'double' : select_fun(function pointer)
}
Run Code Online (Sandbox Code Playgroud)
无论什么类型select_fun(function pointer)
都会调用单个函数.在里面select_fun(function pointer)
,我将有浮动,双重等功能.
根据函数指针,将调用指定的函数.
我不知道我的编程知识是好还是坏,我还需要帮助.
Ada*_*eld 20
你能更具体地说明你想要做什么吗?你不需要做任何特殊的事情来获取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
Run Code Online (Sandbox Code Playgroud)
您可以使用type()
内置函数来检测函数的类型.
比如,如果要检查某个名称是否包含字符串数据,您可以这样做:
if type(this_is_string) == type('some random string'):
# this_is_string is indeed a string
Run Code Online (Sandbox Code Playgroud)
所以在你的情况下,你可以这样做:
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)
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它:
call_option('123') # string_function gets called
call_option(123.456) # float_function gets called
call_option(123) # int_function gets called
Run Code Online (Sandbox Code Playgroud)
我附近没有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)
Run Code Online (Sandbox Code Playgroud)
由于密钥本身与type()函数的值相当,您可以这样做:
def call_option(arg):
func = options[type(arg)]
func(arg)
Run Code Online (Sandbox Code Playgroud)
哪个更优雅:-)保存一些错误检查.
编辑:对于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)
Run Code Online (Sandbox Code Playgroud)