通过本地函数更改函数变量

时间:2018-05-24 05:50:24

标签: python python-3.x

我想通过其辅助函数更改函数中的变量。 我尝试了以下方法:

def f():
    e = 70
    print(e) # prints 70
    def helper(e):
        print(e) # prints 70
        e = 100
        print(e) # prints 100
    helper(e) #function called to change e
    print(e)  # Still prints 70 :( Why?

f() #prints 70, 70, 100, 70

为什么它不改变e的值(我把它作为参数传递而python也没有复制值,所以应该改变f中e的值)? 我怎样才能得到所需的结果?

1 个答案:

答案 0 :(得分:0)

函数e中的

ff的本地,您传递了参数e。但是当您helpere=100内,它是helper范围内的另一个局部变量。因此,您应该从帮助程序返回值并更新e。

你应该这样做,

def f():
    e = 70
    print(e) 
    def helper(d):
        print(d) 
        e = 100
        print(e)
        return e # prints 100
    e = helper(e) 
    print(e)  

f()
相关问题