【发布时间】:2019-05-29 06:46:24
【问题描述】:
我有一个变量 f。如何确定它的类型?这是我的代码,输入到 Python 解释器中,显示使用我在 Google 中找到的许多示例的成功模式时出现错误。 (提示:我对 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
使用 f 函数,我尝试将 type(f) 的返回值转换为字符串,其中 u = str(type(f))。但是当我尝试 u.print() 时,我收到一条错误消息。这对我提出了另一个问题。在 Unix 下,来自 Python 的错误消息会出现在 stderr 还是 stdout 上?
【问题讨论】:
-
您已经通过使用
type获得了它的类型。没有绑定到该类型的function内置变量;类知道自己的名称并不意味着存在具有该名称的变量。 -
以防万一,您希望 Python 也返回函数的结果类型:这在动态语言中是不可能的,因为不同的 Returns 可能返回不同类型的结果。 Python 3 的 function annotations 可能会为您提供帮助,但它们并未强制执行。