问题描述
我目前正在开发一个简单的计算器程序,但在从嵌套函数中获取数据并在另一个嵌套函数中使用它时遇到了问题。
这是我的代码中与此问题相关的部分:
def func():
def func1():
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
def func2():
print(f"{a},{b}")
func1()
func2()
func()
如您所见,func()
被调用,它调用 func1()
和 func2()
。但是,运行此程序会导致 NameError: name 'a' is not defined
带有指向 func2()
主体的错误参考线。
我知道无法在 a,b
中访问 func2()
,因为它们仅在 func1()
中定义,但我不能根据 nonlocal
语句使用 func1()
{3}}:
'非本地语句中列出的名称...必须引用封闭作用域中预先存在的绑定。'
和 func2()
不包含 global
。
更重要的是,我试图避免使用 a
语句或在 b
中定义 func()
和 a
,因为这在任何编程语言中似乎都是糟糕的做法( documentation) 并且可能会在我的程序开发过程中导致意外的副作用。
有没有什么方法可以在 b
中的任何地方声明 func()
和 func1
为可用和可修改的,同时仍然在 def load_db(func):
def wrapper():
print("loading DB")
db = 5
# the db was loaded and is Now passed to the function actually making use of it
func(db)
return wrapper
def load_and_write_db(func):
def wrapper():
print("loading DB")
db = 5
# the db was loaded and is Now passed to the function actually making use of it
# we will get back the changed database
db = func(db)
# Now we write the DB to the disk
print(f"writing DB: {db}")
return wrapper
@load_db
def do_stuff_load_only(*db):
# a function that just consumes the DB,without changing it
print(f"initial DB is {db}")
@load_and_write_db
def do_stuff_load_and_write(*db):
# a function that consumes and chnages the DB (which then needs to be updated on disk)
print(f"initial DB is {db}")
db = 10
print(f"changed DB to {db}")
# returning the new DB
return db
do_stuff_load_only()
do_stuff_load_and_write()
# Output:
#
# loading DB
# initial DB is (5,)
# loading DB
# initial DB is (5,)
# changed DB to 10
# writing DB: 10
中定义它?
解决方法
你只需要在func1中返回它们并将结果传递给func2
def func1():
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
return a,b
那么,
def func2(a,b):
print(f"{a},{b}")
然后当您调用函数时,您将变量 a 和 b 分配给 func1 的结果,并将它们作为参数传递给 func2,
a,b = func1()
func2(a,b)
您可以在 func 范围内初始化变量,但最好将它们作为函数的返回来处理,这样更容易跟踪算法。
,这是范围的问题。
您有 2 种可能性可以让它发挥作用:
1.在 a
中返回 b
和 func1
,并在 func1
中调用 func2
:
def func():
def func1():
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
return (a,b)
def func2():
a,b = func1()
print(f"{a},{b}")
func2()
func()
2.在func2
中定义func1
,声明后在func2
中调用func1
,声明后在func1
中调用func
:强>
def func():
def func1():
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
def func2():
print(f"{a},{b}")
func2()
func1()
func()