Is A Python Function Stored As An Object?
This query is in continuation with link to understand further on this point: In the case of functions, you have an object which has certain fields, which contain e. g. the code
Solution 1:
All this is saying is that, in Python, functions are objects like any other.
For example:
In [5]: def f(): pass
Now f
is an object of type function
:
In [6]: type(f)
Out[6]: function
If you examine it more closely, it contains a whole bunch of fields:
In [7]: dir(f)
Out[7]:
['__call__',
...
'func_closure',
'func_code',
'func_defaults',
'func_dict',
'func_doc',
'func_globals',
'func_name']
To pick one example, f.func_name
is the function's name:
In [8]: f.func_name
Out[8]: 'f'
and f.func_code
contains the code:
In [9]: f.func_code
Out[9]: <code object f at 0x11b5ad0, file "<ipython-input-5-87d1450e1c01>", line 1>
If you are really curious, you can drill down further:
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']
and so on.
(The above output was produced using Python 2.7.3.)
Post a Comment for "Is A Python Function Stored As An Object?"