在python中,局部/全局可变对象的行为与不可变对象的行为有何不同?

2024-09-27 07:21:40 发布

您现在位置:Python中文网/ 问答频道 /正文

场景1:可变对象类列表

def a(l):
    l[0] = 1
    print("\nValue of l = {0} in a()".format(l))

def b(l):
    l = l + [9]
    print("\nValue of l = {0} in b()".format(l))

l = [0]

a(l)
print("\nValue of l = {0} after executing a()".format(l))
b(l)
print("\nValue of l = {0} after executing b()".format(l))

输出

^{pr2}$

问题

  • 在可变对象的上下文中,为什么在b()中对l所做的修改在全局范围内不可见,而对a()的修改却发生在a()中?在

场景2:不可变对象,如整数

def a(l):
    l = 1
    print("\nValue of l = {0} in a()".format(l))
def b(l):
    l = l + 9
    print("\nValue of l = {0} in b()".format(l))

l = 0

a(l)
print("\nValue of l = {0} after executing a()".format(l))
b(l)
print("\nValue of l = {0} after executing b()".format(l))

输出

Value of l = 1 in a()
Value of l = 0 after executing a()
Value of l = 9 in b()
Value of l = 0 after executing b()

问题

  • 在不可变对象的上下文中,为什么在a()和b()中对l所做的修改在全局范围内不可见?在

我和很多人商量过了,但他们无法解释。有人能解释一下这个例子中使用的基本概念吗?在


Tags: of对象informat列表valuedef场景

热门问题