比较类型(my_function)
Comparing with type(my_function)
我有一个函数应该根据传递给它的参数类型进行操作,简单说明:
def operate_according_to_type(argument_passed):
if type(argument_passed) == str:
do string stuff
elif type(argument_passed) == dict:
do dict stuff
elif type(argument_passed) == function:
argument_passed()
def my_function(): pass
operate_according_to_type("Hello world")
operate_according_to_type({"foo": "bar"})
operate_according_to_type(my_function)
现在 type("Hello world")
、type({"foo": "bar"})
和 type(my_function)
将分别 return <class 'str'>
、<class 'dict'>
和 <class 'function'>
,我似乎无法与 function
相比,就像我可以与 str
相比,这个词甚至不是 "reserved".
我该如何进行?我应该继续还是这只是简单的危险?
您可以使用 callable
内置函数检查对象是否可调用:
...
elif callable(argument_passed):
argument_passed()
可以找到更多详细信息 here。
我有一个函数应该根据传递给它的参数类型进行操作,简单说明:
def operate_according_to_type(argument_passed):
if type(argument_passed) == str:
do string stuff
elif type(argument_passed) == dict:
do dict stuff
elif type(argument_passed) == function:
argument_passed()
def my_function(): pass
operate_according_to_type("Hello world")
operate_according_to_type({"foo": "bar"})
operate_according_to_type(my_function)
现在 type("Hello world")
、type({"foo": "bar"})
和 type(my_function)
将分别 return <class 'str'>
、<class 'dict'>
和 <class 'function'>
,我似乎无法与 function
相比,就像我可以与 str
相比,这个词甚至不是 "reserved".
我该如何进行?我应该继续还是这只是简单的危险?
您可以使用 callable
内置函数检查对象是否可调用:
...
elif callable(argument_passed):
argument_passed()
可以找到更多详细信息 here。