首页 > 解决方案 > 是否有可能在 python 中具有依赖于同一级别的另一个函数的函数?

问题描述

我一直在尝试从函数中创建一种代码树,在树中的任何地方我都可以调用一个函数,它将跟随执行该行中的每个下一个函数。我不断收到错误消息,例如在 func2 中说“a 未在第 5 行定义”。

def func1():
    global a
    a = 2
    func2()
def func2():
    global b
    b = a - 1
    func3()

标签: python

解决方案


你可以,但你必须在调用它之前定义函数。


下面的代码示例会产生您遇到的错误。

def func1():
    a = 2
    func2() # <- func2 does not exist yet

def func2():
    b = a - 1
    func3() # <- unless defined above, func3 does not exist either

相反,以下代码应该可以工作

def func3():
    pass

def func2():
    global b
    b = a - 1
    func3() # <- func3 is defined, it will be ok

def func1():
    global a
    a = 2
    func2() # <- func2 is defined too, no problem here

func1()
print(a,b)

推荐阅读