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

问题描述 投票:11回答:3

strtype这样的课程

>>> type("pear")
<class 'str'>
>>> type(str)
<class 'type'>

可以在Python中访问:

>>> str
<class 'str'>
>>> type
<class 'type'>

但是,类functionbuiltin_function_or_method不是。

>>> def foo(): pass
... 
>>> type(foo)
<class 'function'>
>>> type(print)
<class 'builtin_function_or_method'>

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

>>> 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

functionbuiltin_function_or_method有什么特别之处?

python class built-in
3个回答
13
投票

你看到的是函数类型的representation

>>> from types import FunctionType
>>> repr(FunctionType)
"<class 'function'>"

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

>>> def f():
...     pass
... 
>>> type(f) is FunctionType
True
>>> type(lambda: None) is FunctionType
True

“function”不是语法本身,因为输入“def”更容易。

一个修辞问题:如果def是用于解析函数类型的名称,那么what syntax would you use实际上定义了一个函数?


4
投票

类和函数具有固有的名称:

>>> def foo():
...     pass
...
>>> foo
<function foo at 0x10f951400>
>>> foo.__name__
'foo'

附加到对象的名称与用于访问对象的名称无关,但在定义函数(和类)时,它们是相同的。

>>> bar = foo
>>> bar
<function foo at 0x10f951400>

您甚至可以删除用于访问该函数的变量,只要您在其他地方有引用:

>>> funcs = [foo]
>>> funcs[0]
<function foo at 0x10f951400>
>>> del foo
>>> foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
>>> funcs[0]
<function foo at 0x10f951400>
>>> funcs[0].__name__
'foo'

内置函数类型是这样的:没有引用它的变量,但它仍然存在,并且有一个__name__

>>> def foo(): pass
...
>>> type(foo)
<class 'function'>
>>> type(foo).__name__
'function'

3
投票

Type Objecttype()函数(或object.__class__)返回。

您可以获得这些类型对象here的完整列表。

但你也可以创建自己的:

>>> import types
>>> types.new_class('my_made_up_type')
<class 'types.my_made_up_type'>

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

© www.soinside.com 2019 - 2024. All rights reserved.