Why can a function modify some arguments as perceived by the caller, but not others?

前端 未结 11 1381
盖世英雄少女心
盖世英雄少女心 2020-11-21 07:10

I\'m trying to understand Python\'s approach to variable scope. In this example, why is f() able to alter the value of x, as perceived within

11条回答
  •  故里飘歌
    2020-11-21 07:40

    Python is a pure pass-by-value language if you think about it the right way. A python variable stores the location of an object in memory. The Python variable does not store the object itself. When you pass a variable to a function, you are passing a copy of the address of the object being pointed to by the variable.

    Contrasst these two functions

    def foo(x):
        x[0] = 5
    
    def goo(x):
        x = []
    

    Now, when you type into the shell

    >>> cow = [3,4,5]
    >>> foo(cow)
    >>> cow
    [5,4,5]
    

    Compare this to goo.

    >>> cow = [3,4,5]
    >>> goo(cow)
    >>> goo
    [3,4,5]
    

    In the first case, we pass a copy the address of cow to foo and foo modified the state of the object residing there. The object gets modified.

    In the second case you pass a copy of the address of cow to goo. Then goo proceeds to change that copy. Effect: none.

    I call this the pink house principle. If you make a copy of your address and tell a painter to paint the house at that address pink, you will wind up with a pink house. If you give the painter a copy of your address and tell him to change it to a new address, the address of your house does not change.

    The explanation eliminates a lot of confusion. Python passes the addresses variables store by value.

提交回复
热议问题