str
或 type
类
>>> type("pear")
<class 'str'>
>>> type(str)
<class 'type'>
可在 Python 中访问:
>>> str
<class 'str'>
>>> type
<class 'type'>
但是,类 function
和 builtin_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
function
和 builtin_function_or_method
有什么特别之处?
最佳答案
您看到的是 representation函数类型:
>>> from types import FunctionType
>>> repr(FunctionType)
"<class 'function'>"
这是用 def 或其他方式定义的函数的“类型”:
>>> def f():
... pass
...
>>> type(f) is FunctionType
True
>>> type(lambda: None) is FunctionType
True
您在表示中看到的字符串来自每个对象的 __name__
属性:
>>> type(print).__name__
'builtin_function_or_method'
>>> FunctionType.__name__
'function'
“function”本身不是语法,因为输入“def”更容易。
反问句:如果 def
是用于解析函数类型的名称,则 what syntax would you use实际定义一个函数?
关于python - 为什么 `function` 不是 Python 中的关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52122632/