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

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

    My general understanding is that any object variable (such as a list or a dict, among others) can be modified through its functions. What I believe you are not able to do is reassign the parameter - i.e., assign it by reference within a callable function.

    That is consistent with many other languages.

    Run the following short script to see how it works:

    def func1(x, l1):
        x = 5
        l1.append("nonsense")
    
    y = 10
    list1 = ["meaning"]
    func1(y, list1)
    print(y)
    print(list1)
    

提交回复
热议问题