简体   繁体   中英

Is Scope the same of variables and lists in Python?

a = 1.111111
b = ["a", "b"]


def adder(x, y):
    x = x *100000
    y[0] = "Herman"
    return x, y

print a
print b
print ""

adder(a,b)

print a # 1.111111 - has not updated
print b # ['Herman', 'b'] - has updated even if list is in gobal scope

Is Scope the same for lists and vars and other objects in Python? In the test above, the var a was not updated when I called/invoked the function adder, however, the list was updated. This would imply that global vars are not changeable from within functions, but that lists and other data container objects like dictionaries are.

Is that correct? Is there any easy way to model this idea in of scope mentally in my head?

每当将列表传递给函数时,您都将传递其地址,因此可以在函数中对其进行更新,而对于变量,则需要通过引用将其传递以使其成功更新。

Variables (re)defined within a function are local by default. x in your case falls in this category. But y[0] = "Herman" is not redefining y , it's mutating it by reassigning its first element. Thus it's not considered local.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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