我有一个变量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'>
当前回答
任何函数都是一个类,所以你可以取实例x的类名并比较:
if(x.__class__.__name__ == 'function'):
print "it's a 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!
使用isinstance()和type(),它们都是Python中的内置函数,你可以检查它是否是一个函数,这样你就不需要导入任何东西:
def test():
pass
print(isinstance(test, type(test)))
输出:
True
任何函数都是一个类,所以你可以取实例x的类名并比较:
if(x.__class__.__name__ == 'function'):
print "it's a function"
下面是一个“repr方法”来检查它。它也适用于。
def a():pass
type(a) #<class 'function'>
str(type(a))=="<class 'function'>" #True
b = lambda x:x*2
str(type(b))=="<class 'function'>" #True
如果值是可调用的,代码将继续执行调用,只需执行调用并捕获TypeError。
def myfunc(x):
try:
x()
except TypeError:
raise Exception("Not callable")