如何在Python中检查函数类型? [英] How to check for a function type in Python?

查看:182
本文介绍了如何在Python中检查函数类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个东西清单,其中一些也可以是函数.如果它是一个函数,我想执行它.为此,我进行了类型检查.这通常适用于其他类型,例如str,int或float.但是对于某个功能,它似乎不起作用:

I've got a list of things, of which some can also be functions. If it is a function I would like to execute it. For this I do a type-check. This normally works for other types, like str, int or float. But for a function it doesn't seem to work:

>>> def f():
...     pass
... 
>>> type(f)
<type 'function'>
>>> if type(f) == function: print 'It is a function!!'
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'function' is not defined
>>>

有人知道我如何检查函数类型吗?

Does anybody know how I can check for a function type?

推荐答案

不要检查类型,请检查操作.您实际上并不在乎它是否是一个函数(例如,它可能是带有__call__方法的类实例)-您只在乎是否可以调用它.因此,请使用callable(f).

Don't check types, check actions. You don't actually care if it's a function (it might be a class instance with a __call__ method, for example) - you just care if it can be called. So use callable(f).

这篇关于如何在Python中检查函数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆