如何在嵌套函数中共享函数变量?

时间:2018-11-29 01:46:23

标签: python python-3.x

已更新:

如何在嵌套函数中使用函数变量?我在以下示例中简化了我的问题:

def build():
    n = 1 # code to parse rpm package minor version from file
    f = min_ver(n) # update minor version
    return

def min_ver(n):
    n = 2 # this is defined by another process, not set intentionally
    s =  1 + n # still need the original value from build()
    return s

实际用例是我从磁盘'n'中获取ex1()中已解析的rpm软件包次要版本值。从ex1()执行ex2()后,它将删除旧软件包,并使用新的次要版本构建新的rpm软件包。因此,当它在嵌套函数中调用ex1()的值时,它不会更改为新版本。

在传递给嵌套函数的新值'n'之前,如何在嵌套函数中保持原始的'n'值?

2 个答案:

答案 0 :(得分:2)

一种简单的方法是将变量作为参数传递给ex2

def build():
    n = int(1)
    f = ex2(n) # pass the value to the next function
    n = int(5) 
    return 

def min_ver(n_old):
    n = 2
    s =  1 + n_old # use the n that was passed in
    return s

答案 1 :(得分:0)

如果将ex2()实际嵌套,则可以访问外部变量。

def ex1():
    n = int(1)
    def ex2():
        s =  1 + n
        return(s)
    f = ex2()
    n = int(5) # done with nested value, rewrite new value
    return()

我想,您可能想返回fn而不是一个空元组。

您不必说int(1),而只需说1。一切,包括整数和字符串,都是python中的隐式对象。

相关问题