【问题标题】:Why is the type of a function <class 'NoneType'>? [closed]为什么函数的类型是<class 'NoneType'>? [关闭]
【发布时间】:2021-07-31 05:42:43
【问题描述】:

运行以下代码后。我观察到print() 的返回类型是无。请解释一下为什么会这样?

>>> v = print(7)                                                                                                                     >>> v                                                                                                                   >>> type(v)                                                                                                             <class 'NoneType'>                                                                                                      >>>  
>>> type(print(y))
7
<class 'NoneType'>
>>> type(None)
<class 'NoneType'>

【问题讨论】:

  • type(print) 返回函数类型,type(print()) 返回函数返回值类型
  • 您没有将v 声明为函数,而是将其声明为特定函数调用(返回None)的返回值。如果您使用v = printv = lambda: print(y),那么v 将是一个函数,您的type 调用将显示&lt;class 'function'&gt;
  • 您输入&gt;&gt;&gt; v 并得到输出7 的部分不会真正发生。它不会给出任何输出。
  • 现在我已经纠正了错别字

标签: python python-3.x function nonetype


【解决方案1】:

你需要使用:

type(print)

如果你添加括号,它会调用函数,type() 会给你返回值的类型

【讨论】:

    【解决方案2】:

    如果一个函数没有返回任何东西,它在 python 中返回 None。

    您将打印与返回混淆了。 print函数的工作就是将值转换为字符串并打印,它不返回任何内容,所以它是'NoneType'。

    更详细的解释可以参考this

    【讨论】:

      猜你喜欢
      • 2021-09-24
      • 1970-01-01
      • 2015-07-29
      • 2015-07-01
      • 2011-09-22
      • 1970-01-01
      • 2016-10-06
      • 2014-09-19
      • 1970-01-01
      相关资源
      最近更新 更多