简体   繁体   English

在函数中的全局列表上使用 append() 方法(Python)

[英]Using append() method on a global list in a function (Python)

I am having issues understanding how global variables can or cannot be edited within the local scope of functions, please see the two example codes I have provided which contrast eachother:我在理解如何在函数的局部范围内编辑全局变量时遇到问题,请参阅我提供的两个示例代码,它们相互对比:

Example 1示例 1

    def function():
        x[0] = True
    x = [False] # global variable
    function()
    print(x)  # True

Example 2示例 2

    def function():
        z = True
    z = False # global variable
    function()
    print(z)  # False

I was of the understanding that global variables cannot be edited within a local scope (inside a function) unless they are explicitly called globally ie (global "variable_name"), however example 1 indicates that when dealing with lists and using the append method, I can in-fact edit the real global variable without having to call it with the explicit global term.我的理解是全局变量不能在局部范围内(在函数内部)进行编辑,除非它们被明确地全局调用,即(全局“variable_name”),但是示例 1 表明在处理列表和使用 append 方法时,我可以事实上编辑真正的全局变量,而不必使用显式全局项调用它。 Where as in example 2, I am unable to re-assign the global variable which is contrary to example 1. Please explain why this is the case, does the append method or lists in particular interact with global/local scope rules differently?在示例 2 中,我无法重新分配与示例 1 相反的全局变量。请解释为什么会出现这种情况,特别是 append 方法或列表与全局/局部范围规则的交互是否不同?

Lists are mutable, so while the variable can not be edited (assigned to another list for example) the contents of the list may be modified and the variable will still point to the same list, so the variable is untouched.列表是可变的,所以当变量不能被编辑(例如分配给另一个列表)时,列表的内容可能会被修改,变量仍然指向同一个列表,所以变量不会被修改。

Try:尝试:

def function():
    x = [True]

x = [False] # global variable
function()
print(x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM