为什么`function`不是Python中的关键字?

mul*_*rse 11 python class built-in

str或等的类type

>>> type("pear")
<class 'str'>
>>> type(str)
<class 'type'>
Run Code Online (Sandbox Code Playgroud)

可以在Python中访问:

>>> str
<class 'str'>
>>> type
<class 'type'>
Run Code Online (Sandbox Code Playgroud)

然而,类functionbuiltin_function_or_method不.

>>> def foo(): pass
... 
>>> type(foo)
<class 'function'>
>>> type(print)
<class 'builtin_function_or_method'>
Run Code Online (Sandbox Code Playgroud)

它们显示为内置类但尝试访问它们会引发名称错误:

>>> function
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'function' is not defined
>>> builtin_function_or_method
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'builtin_function_or_method' is not defined
Run Code Online (Sandbox Code Playgroud)

有什么特别的functionbuiltin_function_or_method

wim*_*wim 14

你看到的是函数类型的表示:

>>> from types import FunctionType
>>> repr(FunctionType)
"<class 'function'>"
Run Code Online (Sandbox Code Playgroud)

这是用def或其他方式定义的函数的"类型":

>>> def f():
...     pass
... 
>>> type(f) is FunctionType
True
>>> type(lambda: None) is FunctionType
True
Run Code Online (Sandbox Code Playgroud)

"function"不是语法本身,因为输入"def"更容易.

一个修辞问题:如果__name__用于解析函数类型的名称,那么您将使用什么语法来实际定义函数?


Joe*_*don 3

A从函数 (或)Type Object返回。type()object.__class__

您可以在此处获取这些类型对象的完整列表。

但您也可以创建自己的:

>>> import types
>>> types.new_class('my_made_up_type')
<class 'types.my_made_up_type'>
Run Code Online (Sandbox Code Playgroud)

所以它是某些对象(如内置函数)返回的类型对象(即:)types.BuiltinFunctionType,但这些类型对象不是内置类,所以难怪它们没有在解释器中定义