只是出于好奇,我想知道这个..
我知道内部函数的范围仅限于外部函数体,但仍然有什么办法可以让我们可以在其范围之外访问内部函数变量或在其范围之外调用内部函数?
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]:
最佳答案
>>> 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
关于python - 我们可以使用外部函数在python的外部函数范围之外访问内部函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11625923/