这一切都说明,在 Python 中,函数和其他对象一样都是对象。
例如:
In [5]: def f(): pass
Now f
是一个类型的对象function
:
In [6]: type(f)
Out[6]: function
如果你仔细检查它,它包含一大堆字段:
In [7]: dir(f)
Out[7]:
['__call__',
...
'func_closure',
'func_code',
'func_defaults',
'func_dict',
'func_doc',
'func_globals',
'func_name']
举一个例子,f.func_name
是函数的名称:
In [8]: f.func_name
Out[8]: 'f'
and f.func_code
包含代码:
In [9]: f.func_code
Out[9]: <code object f at 0x11b5ad0, file "<ipython-input-5-87d1450e1c01>", line 1>
如果你真的很好奇,你可以进一步深入:
In [10]: dir(f.func_code)
Out[10]:
['__class__',
...
'co_argcount',
'co_cellvars',
'co_code',
'co_consts',
'co_filename',
'co_firstlineno',
'co_flags',
'co_freevars',
'co_lnotab',
'co_name',
'co_names',
'co_nlocals',
'co_stacksize',
'co_varnames']
等等。
(以上输出是使用 Python 2.7.3 生成的。)