python - 在 python 函数中访问函数

标签 python

给定函数中的函数,如何从外部函数调用内部函数?

例如

def a():
    print 'a'
    def b():
        print 'b'
        def c():
            print 'c'

def d():
    # how would I now call a, b and c from here?
    def e():
        # how would I call a, b and c from here as well?

是的,我知道这是可怕的代码结构,不应该这样做 - 但你是怎么做到的?

编辑:有什么方法可以使用装饰器做到这一点?

最佳答案

你不能。 bca 中的局部变量,除非 a 正在执行,否则不存在。

(因为这些是常量,从技术上讲,您可以通过 a.__code__.co_consts 访问它们,但这不是真正的解决方案,即使您可以接受糟糕的代码结构。您将不得不使用 exec 执行函数,你不能向它传递参数。)

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

相关文章:

python - lgb.train ValueError : The truth value of an array with more than one element is ambiguous. 使用 a.any() 或 a.all()

python - 使用 docstring 和 "Not Implemented"异常在 Eclipse 和 Pydev 中预填充新函数

python - 从字典列表创建 Pandas 数据框,字典键作为列

python - 通过 Tensorflow 中的段长度计算 tf.math.segment_sum 中所需的段 ID

python - 在本地运行我的工作 web 应用程序,但无法访问正确的站点

python - 游戏 : a fast way to find what is on screen before displaying it with insane amount of objects

python - 无法使用 boto 2.31.1 创建 cloudsearch int 索引字段

python - 如何绘制动画图

python - 获取新的唯一列表,仅包含原始列表中最后出现的元素

python - Flask-Restful:通过 POST 请求将列表传递到 MongoDB