可以使用type()
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没有计划太多所以可能有一些错误,但你应该明白。
编辑:按@亚当的建议,也有内置式常量,你可以对证直接,所以更好的做法是:
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)
而且,由于密钥本身与类型()函数的值相当,你可以这样做:
def call_option(arg):
func = options[type(arg)]
func(arg)
哪个更优雅:-)保存一些错误检查。
编辑:而对于ctypes的支持,一些摆弄周围后,我发现ctypes的[type_name_here]实际上implented为类。所以这个方法仍然有效,你只需要使用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中的特定于类型的处理。此外,由于select_fun(aFunction)每次都是相同的事情,因此不清楚从字典中获取select_fun(aFunction)的哪个点。 – 2008-12-31 11:24:06