python查找函数的类型 [英] python find the type of a function

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

问题描述

我有一个变量f。如何确定其类型?这是我的代码,输入到python解释器中,显示我使用Google发现的许多示例的成功模式都出错。 (提示:我对Python很陌生。)

I have a variable f. How can I determine its type? Here is my code, typed into a python interpreter, showing that I get an error using the successful pattern of the many examples I have found with Google. (Hint: I am very new to Python.)

>>> i=2; type(i) is int
True
>>> def f():
...     pass
... 
>>> type(f)
<class 'function'>
>>> type(i)
<class 'int'>
>>> type(f) is function
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'function' is not defined
>>> f=3
>>> type(f) is int
True

使用fa函数,我尝试转换返回值将type(f)转换为字符串,其中u = str(type(f))。但是当我尝试u.print()时,我收到一条错误消息。这给我提出了另一个问题。在Unix下,来自Python的错误消息会出现在stderr还是stdout上?

With f a function, I tried casting the return value of type(f) to a string, with u = str(type(f)). But when I tried u.print() I got an error message. This raises another question for me. Under Unix do error messages from Python come on stderr or stdout?

推荐答案

使用pythonic方法检查函数类型的方法是 isinstance

The pythonic way to check the type of a function is using isinstance builtin.

i = 2
type(i) is int #not recommended
isinstance(i, int) #recommended

Python包含 类型 模块,用于检查其他功能。

Python includes a types module for checking functions among other things.


它还定义了
标准Python解释器使用的某些对象类型的名称,但没有像int或
str这样的内置函数公开。

It also defines names for some object types that are used by the standard Python interpreter, but not exposed as builtins like int or str are.

因此,要检查对象是否为函数,可以使用以下类型的模块

So, to check if an object is a function, you can use the types module as follows

def f():
    print("test")    
import types
type(f) is types.FunctionType #Not recommended but it does work
isinstance(f, types.FunctionType) #recommended.

但是,请注意,对于内置函数,它将打印为false。如果您还希望包含这些内容,请按以下步骤检查

However, note that it will print false for builtin functions. If you wish to include those as well, then check as follows

isinstance(f, (types.FunctionType, types.BuiltinFunctionType))

但是,如果您只想要特定的功能,请使用上面的内容。最后,如果只关心它是否是函数,可调用或方法之一,则只需检查它的行为是否类似于可调用。

However, use the above if you only want specifically functions. Lastly, if you only care about checking if it is one of function,callable or method, then just check if it behaves like a callable.

callable(f)

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

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