Python overwriting variables in nested functions

前端 未结 4 2050
天涯浪人
天涯浪人 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:19

    You can also get around this by using function attributes:

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

    Clarification: this works in both python 2.x and 3.x.

提交回复
热议问题