我们可以使用外部函数在python中访问其外部函数范围之外的内部函数吗?

NIl*_*rma 5 python scope function

只是为了好奇我想知道这个..
我知道内部函数的范围仅限于外部函数体,但仍然有任何方式使我们可以访问其范围之外的内部函数变量或者调用外部函数它的范围?

In [7]: def main():
   ...:     def sub():
   ...:         a=5
   ...:         print a
   ...:         

In [8]: main()

In [9]: main.sub()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/home/dubizzle/webapps/django/dubizzle/<ipython-input-9-3920726955bd> in <module>()
----> 1 main.sub()

AttributeError: 'function' object has no attribute 'sub'

In [10]: 
Run Code Online (Sandbox Code Playgroud)

Joh*_*ooy 6

>>> def main():
...     def sub():
...         a=5
...         print a
... 
>>> main.__code__.co_consts
(None, <code object sub at 0x2111ad0, file "<stdin>", line 2>)
>>> exec main.__code__.co_consts[1]
5
Run Code Online (Sandbox Code Playgroud)

  • 这适用于大多数python实现吗? (2认同)