这是因为您在函数 2 中将 mylist 分配给了其他对象:
在python中,如果你将一个可变对象传递给一个函数,那么它被称为通过引用传递,如果你传递一个不可变对象,那么它被称为按值传递。
mylist = [1,2,3,4]
def changeme( mylist ):
print (id(mylist)) #prints 180902348
#at this point the local variable mylist points to [10,20,30]
mylist = [1,2,3,4]; #this reassignment changes the local mylist,
#now local mylist points to [1,2,3,4], while global mylist still points to [10,20,30]
print (id(mylist)) #prints 180938508 #it means both are different objects now
print ("Values inside the function: ", mylist)
return
mylist = [10,20,30];
changeme( mylist );
print ("Values outside the function: ", mylist)
第一:
def changeme( mylist ):
print (id(mylist)) #prints 180902348
mylist.append([1,2,3,4]); #by this it mean [10,20,30].append([1,2,3,4])
#mylist is just a label pointing to [10,20,30]
print (id(mylist)) #prints 180902348 , both point to same object
print ("Values inside the function: ", mylist)
return
mylist = [10,20,30];
changeme( mylist );
print ("Values outside the function: ", mylist)