python - 是否有可能在 python 中具有依赖于同一级别的另一个函数的函数?
问题描述
我一直在尝试从函数中创建一种代码树,在树中的任何地方我都可以调用一个函数,它将跟随执行该行中的每个下一个函数。我不断收到错误消息,例如在 func2 中说“a 未在第 5 行定义”。
def func1():
global a
a = 2
func2()
def func2():
global b
b = a - 1
func3()
解决方案
你可以,但你必须在调用它之前定义函数。
下面的代码示例会产生您遇到的错误。
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)
推荐阅读
- python - 在pycharm中安装beautifulsoup后导入错误
- operating-system - 设置进程状态
- python - AWS Glue - Boto3 创建触发器问题
- angular - 此条件将始终返回 'false',因为类型 'string' 和 '() => string' 没有重叠
- android - 从firebase检索值并将它们提交到列表视图的Android问题
- selenium - Selenium => 4BUTTON 具有相同的 href 、相同的类、相同的文本想要点击 4
- java - Java 代码无法在 android studio 中运行。端口通讯
- json - 如何获取存储在数据库中的日期作为 Clojure 中的字符串?
- javascript - 如何在 Typescript 中为 Map 的类型别名定义索引签名?
- r - R 中的内存问题。在 rmarkdown 中渲染站点时,我可以使用 rm(list=ls()) 和 .rs.restartR() 清除内存吗?