gpt4 book ai didi

python - 使变量有条件地全局

转载 作者:太空宇宙 更新时间:2023-11-03 14:53:57 24 4
gpt4 key购买 nike

假设我需要运行一个带有循环的函数,直到满足条件为止。为了使函数正常工作,我只允许在函数中返回一个值,但是一旦条件清除,我想将我执行的一些计算带入全局范围。我不允许使用 return 命令来执行此操作,因此我决定在 post 中全局化变量。这会发出警告,但似乎工作正常。这是最好的做事方式吗?

这是一个例子:

def check_cond(x,cond):
return (x - cond,3)

def loop(x,func):
relevant_value = 0
while x > 0:
local_expensive_calculation = 1 #use your imagination
x = func(x,local_expensive_calculation)[0]
relevant_value += func(x,local_expensive_calculation)[1]
if x == 0:
global local_expensive_calculation
return relevant_value

x = 4
loop(x,check_cond)

#then do stuff with local_expensive_calculation, which is now global

最佳答案

这可能会稍微滥用系统,但您可以将变量设置为函数的属性,然后稍后通过该命名空间访问它:

def check_cond(x,cond):
return (x - cond,3)

def loop(x,func):
relevant_value = 0
while x > 0:
local_expensive_calculation = 1 #use your imagination
x = func(x,local_expensive_calculation)[0]
relevant_value += func(x,local_expensive_calculation)[1]
if x == 0:
loop.local_expensive_calculation = local_expensive_calculation
return relevant_value

x = 4
loop(x,check_cond)

print loop.local_expensive_calculation

关于python - 使变量有条件地全局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45721372/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com