请允许我再次编辑。这些概念是我通过尝试错误和互联网学习python的经验,主要是stackoverflow。有错误,有帮助。
Python 变量使用引用,我认为引用是来自名称、内存地址和值的关系链接。
当我们做B = A时,我们实际上创建了一个昵称A,现在A有2个名字,A和B。当我们调用B时,我们实际上是在调用A。我们创建一个值为的墨水其他变量,而不是创建一个新的相同值,这就是我们所说的引用。这种想法会导致两个问题。
当我们这样做时
A = [1]
B = A # Now B is an alias of A
A.append(2) # Now the value of A had been changes
print(B)
>>> [1, 2]
# B is still an alias of A
# Which means when we call B, the real name we are calling is A
# When we do something to B, the real name of our object is A
B.append(3)
print(A)
>>> [1, 2, 3]
当我们将参数传递给函数时会发生这种情况
def test(B):
print('My name is B')
print(f'My value is {B}')
print(' I am just a nickname, My real name is A')
B.append(2)
A = [1]
test(A)
print(A)
>>> [1, 2]
我们将 A 作为函数的参数传递,但该函数中该参数的名称是 B。
同一个名字不同。
因此,当我们执行B.append 时,我们正在执行A.append
当我们将参数传递给函数时,我们传递的不是变量,而是别名。
这两个问题来了。
- 等号总是创建一个新名称
A = [1]
B = A
B.append(2)
A = A[0] # Now the A is a brand new name, and has nothing todo with the old A from now on.
B.append(3)
print(A)
>>> 1
# the relation of A and B is removed when we assign the name A to something else
# Now B is a independent variable of hisown.
等号是明确全新名称的声明,
这是我的脑震荡部分
A = [1, 2, 3]
# No equal sign, we are working on the origial object,
A.append(4)
>>> [1, 2, 3, 4]
# This would create a new A
A = A + [4]
>>> [1, 2, 3, 4]
和功能
def test(B):
B = [1, 2, 3] # B is a new name now, not an alias of A anymore
B.append(4) # so this operation won't effect A
A = [1, 2, 3]
test(A)
print(A)
>>> [1, 2, 3]
# ---------------------------
def test(B):
B.append(4) # B is a nickname of A, we are doing A
A = [1, 2, 3]
test(A)
print(A)
>>> [1, 2, 3, 4]
第一个问题是
-
和等式的左边总是一个全新的名称,新的变量,
-
除非右边是一个名字,比如B = A,否则只创建一个别名
第二个问题,有些东西是永远不会改变的,我们不能修改原来的,只能创建一个新的。
这就是我们所说的不可变。
当我们执行A= 123 时,我们会创建一个包含名称、值和地址的字典。
当我们做B = A时,我们将地址和值从A复制到B,所有对B的操作都影响A的值的相同地址。
当涉及到字符串、数字和元组时。价值和地址这对永远不会改变。当我们将str放到某个地址时,它立即被锁定,所有修改的结果都会放到其他地址中。
A = 'string' 将创建一个受保护的值并存储字符串 'string' 。目前还没有内置函数或方法可以修改像list.append这样的语法的字符串,因为这段代码修改了地址的原始值。
字符串、数字或元组的值和地址是受保护的、锁定的、不可变的。
我们只能通过A = B.method的语法来处理字符串,我们必须创建一个新名称来存储新的字符串值。
如果您仍然感到困惑,请扩展此讨论。
这个讨论帮助我一劳永逸地弄清楚可变/不可变/引用/参数/变量/名称,希望这也可以对某人有所帮助。
##############################
无数次修改了我的答案,意识到我不必说什么,python 已经解释了自己。
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)
这个恶魔不是引用/值/可变与否/实例、命名空间或变量/列表或str,它是语法,等号。