Python overwriting variables in nested functions

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

    This happens to me way too often, when I was writing a function and I suddenly realize that it could be a good idea to have a smaller helper function, but not really useful anywhere else. which naturally makes me want to define it inside as a nested function.

    but I had experience with JAVA anonymous object(ie: define a runnable), and the rule was that the anonymous object makes a hard copy of its outer environment, in this case variables of the outer scope. Thus if the outer variable is a immutable (int,char), they can not be modified by anonymous object as they are copied by value whereas if its a mutable (collection, objects), they can be changed...since they are copied by "pointer" (their address in memory)

    if you know about programming, think of it as pass by value and pass by reference.

    in python, it's very much the same. x=123 is an assignment, they give the variable x a new meaning (not modify the old x), list[i]/dict[key] are object access operations, they really modify things

    to conclude, you need a mutable object...in order to modify (even though you can access a tuple using [], you can not use it here since its not mutable)

提交回复
热议问题