【问题标题】:Comparing with type(my_function) [duplicate]与类型(my_function)比较 [重复]
【发布时间】:2020-03-10 11:20:12
【问题描述】:

我有一个函数应该根据传入的参数类型进行操作,简单说明:

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) 将分别返回 <class 'str'><class 'dict'><class 'function'>,但我似乎无法与 function 相比,就像我与 str 相比,这个词甚至没有“保留”。

我应该如何进行?我应该继续进行吗?还是这只是很危险?

【问题讨论】:

标签: python python-3.x types comparison


【解决方案1】:

您可以使用callable 内置函数检查对象是否可调用:

...
elif callable(argument_passed):
    argument_passed()

更多详情请见here

【讨论】:

  • 谢谢!对不起,重复。像示例这样的案例总体上被认为是不好的做法还是很好?
  • @PierreMDL 检查参数的类型绝不是一个坏习惯:)
猜你喜欢
  • 1970-01-01
  • 2019-01-23
  • 2017-01-10
  • 1970-01-01
  • 1970-01-01
  • 2016-07-26
  • 2011-05-05
  • 2010-11-15
  • 2020-12-30
相关资源
最近更新 更多