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

前端 未结 11 1200
盖世英雄少女心
盖世英雄少女心 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 08:01

    I had modified my answer tons of times and realized i don't have to say anything, python had explained itself already.

    a = 'string'
    a.replace('t', '_')
    print(a)
    >>> 'string'
    
    a = a.replace('t', '_')
    print(a)
    >>> 's_ring'
    
    b = 100
    b + 1
    print(b)
    >>> 100
    
    b = b + 1
    print(b)
    >>> 101
    
    
    def test_id(arg):
        c = id(arg)
        arg = 123
        d = id(arg)
        return
    
    a = 'test ids'
    b = id(a)
    test_id(a)
    e = id(a)
    
    # b = c  = e != d
    
    # this function do change original value
    del change_like_mutable(arg):
        arg.append(1)
        arg.insert(0, 9)
        arg.remove(2)
        return
    
    test_1 = [1, 2, 3]
    change_like_mutable(test_1)
    
    
    
    # this function doesn't 
    def wont_change_like_str(arg):
         arg = [1, 2, 3]
         return
    
    
    test_2 = [1, 1, 1]
    wont_change_like_str(test_2)
    print("Doesn't change like a imutable", test_2)
    
    

    This devil is not the reference / value / mutable or not / instance, name space or variable / list or str, IT IS THE SYNTAX, EQUAL SIGN.

提交回复
热议问题