python - 函数是python中类的对象?

标签 python function

我读到函数是 python 中类的对象。为了进一步理解,我做了以下操作:

>>> a=10
>>> a.__class__
<type 'int'>
>>> int.__class__
<type 'type'>
>>>
>>>
>>> def T1():
...     print 'test'
...
>>> T1.__class__
<type 'function'>
>>> function.__class__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'function' is not defined

问:为什么解释器在第二种情况下会抛出错误,而在第一种情况下不会?我期待它返回 <type 'type'> .请纠正我的理解。

最佳答案

有一个函数类型,但没有内置的名称。您可以在 types 模块下找到另一个引用:

>>> import types
>>> def T1():
...     pass
...     
>>> T1.__class__ is types.FunctionType
True
>>> print(repr(types.FunctionType))
<class 'function'>

因此,这里唯一的区别是 function 不是内置名称,这与 int 等名称不同。如果出于某种原因你想在你的命名空间中使用该名称,你可以绑定(bind)它:

>>> function = type(lambda: 0)
>>> function
<class 'function'>

关于python - 函数是python中类的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41942661/

相关文章:

python - 在 Python 中打印不同级别

javascript - 提交后隐藏一个div

javascript - 使用自定义原型(prototype)在 javascript 中创建函数

function - 在语言环境中使用逗号作为小数点标记分隔函数的参数

python - django 中的 url 中带分号的 url 需要什么模式

python - 为什么 pysftp 库中的 chdir 不影响 pysftp 库中的执行?

python - 从 excel 文件中读取缓存的外部字段,结果与我在 excel 中看到的不同

python - 如何停止在 Python 中打印 OpenCV 错误消息

javascript - 如何使脚本在窗口大小调整时重新运行?

javascript - 选择函数的子集作为字符串并评估