我有一个变量x,我想知道它是否指向一个函数。
我希望我能做一些像这样的事情:
>>> isinstance(x, function)
但这给了我:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function' is not defined
我选这个是因为
>>> type(x)
<type 'function'>
我有一个变量x,我想知道它是否指向一个函数。
我希望我能做一些像这样的事情:
>>> isinstance(x, function)
但这给了我:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function' is not defined
我选这个是因为
>>> type(x)
<type 'function'>
当前回答
根据之前的回复,我想出了这个:
from pprint import pprint
def print_callables_of(obj):
li = []
for name in dir(obj):
attr = getattr(obj, name)
if hasattr(attr, '__call__'):
li.append(name)
pprint(li)
其他回答
注意,Python类也是可调用的。
要获得函数(这里的函数指的是标准函数和lambdas),请使用:
import types
def is_func(obj):
return isinstance(obj, (types.FunctionType, types.LambdaType))
def f(x):
return x
assert is_func(f)
assert is_func(lambda x: x)
任何函数都是一个类,所以你可以取实例x的类名并比较:
if(x.__class__.__name__ == 'function'):
print "it's a function"
在一些答案中提到的使用hasattr(obj, '__call__')和callable(.)的解决方案有一个主要缺点:对于具有__call__()方法的类和类的实例,它们都返回True。如。
>>> import collections
>>> Test = collections.namedtuple('Test', [])
>>> callable(Test)
True
>>> hasattr(Test, '__call__')
True
检查一个对象是否是用户定义的函数(只有a that)的一个正确方法是使用isfunction(.):
>>> import inspect
>>> inspect.isfunction(Test)
False
>>> def t(): pass
>>> inspect.isfunction(t)
True
如果您需要检查其他类型,请查看inspect -检查活动对象。
在Python3中,我提出了type (f) == type (lambda x:x),如果f是一个函数,则输出True,如果不是则输出False。但我想我更喜欢isinstance (f, types.FunctionType),它感觉不那么特别。我想写type (f) is function,但这行不通。
函数只是一个带有__call__方法的类,所以你可以这样做
hasattr(obj, '__call__')
例如:
>>> hasattr(x, '__call__')
True
>>> x = 2
>>> hasattr(x, '__call__')
False
这是“最好”的方法,但这取决于你为什么需要知道它是可调用的还是注释的,你可以把它放在try/execpt块中:
try:
x()
except TypeError:
print "was not callable"
如果try/except比doing if hasattr(x, '__call__'): x()更适合Python,这是有争议的。我会说hasattr更准确,因为你不会意外地捕捉到错误的TypeError,例如:
>>> def x():
... raise TypeError
...
>>> hasattr(x, '__call__')
True # Correct
>>> try:
... x()
... except TypeError:
... print "x was not callable"
...
x was not callable # Wrong!