Python overwriting variables in nested functions

前端 未结 4 2056
天涯浪人
天涯浪人 2020-11-28 09:33

Suppose I have the following python code:

def outer():
    string = \"\"
    def inner():
        string = \"String was changed by a nested function!\"
    i         


        
4条回答
  •  囚心锁ツ
    2020-11-28 10:15

    In Python 3.x, you can use the nonlocal keyword:

    def outer():
        string = ""
        def inner():
            nonlocal string
            string = "String was changed by a nested function!"
        inner()
        return string
    

    In Python 2.x, you could use a list with a single element and overwrite that single element:

    def outer():
        string = [""]
        def inner():
            string[0] = "String was changed by a nested function!"
        inner()
        return string[0]
    

提交回复
热议问题