Python中的可变性,为什么会发生? [重复]

问题描述 投票:0回答:1

因此,我试图使变异性更好地进入我的大脑,我看到很多有经验的人有时会挣扎。

我在这里做了这个小的测试代码:

x = 1
def test():
    x = 2
test()
print(x) #1


x = 1
def test():
    global x
    x = 2
test()
print(x) #2


x = [1]
def test():
    x = [2]
test()
print(x) #[1]


x = [1]
def test():
    global x
    x = [2]
test()
print(x) # [2]


x = [1]
def test():
    x[0] = 2
test()
print(x) #[2]

除了倒数第二个和倒数第二个之间的区别之外,其他一切我都很清楚。确切的规则是什么。我注意到可以更改对象的值,但不能更改对象类型本身,或者我理解这是错误的吗?

python list immutability
1个回答
1
投票
# case 1
x = 1
def test():
    x = 2
test()
print(x) #1

# case 2
x = 1
def test():
    global x
    x = 2
test()
print(x) #2

在情况1中,x内的变量test在本地范围内,因此更改其值不会更改在test外部声明的x的值,因此不会使在x外部声明的test突变。 。

在情况2中,x内的变量test处于全局范围内,因此更改其值的确会更改test外部声明的x的值,因此会使x外部的test发生突变。


# case 3
x = [1]
def test():
    global x
    x = [2]
test()
print(x) # [2]

# case 4
x = [1]
def test():
    x[0] = 2
test()
print(x) #[2]

在情况3中,x中的列表test的全局作用域为test之外的列表的引用的引用,但是当您为x分配新列表时,将为此列表创建一个新引用[2]和对该新列表进行更改不会使test外部声明的列表中的值发生更改。

[在情况4中,x方法内的列表test保留对在函数test外部声明的列表的相同实例的引用,当您调用x[0]时,您不会更改对该列表的引用但是,您是将2的值分配给同一列表内的index 0,这会使外部列表发生变化。

© www.soinside.com 2019 - 2024. All rights reserved.