Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

function - What is the scope of argument variables in python?

Consider the following cases:

Case 1:

def fun(arg):
    
    arg += 1
    
my_var = 1
fun(my_var)
print(my_var)
>> 1

Case 2:

def fun(arg):
    
    arg += [4]
    
my_var = [1,2,3]
fun(my_var)
print(my_var)
>> [1, 2, 3, 4]

Case 3:

def fun(arg):
    
    arg = arg + [4]
    
my_var = [1,2,3]
fun(my_var)
print(my_var)
>> [1, 2, 3]

Case 4:

def fun(arg):
    
    print(arg)

fun("Hi")
print(arg)
>> Hi
Traceback (most recent call last):
  File "<string>", line 8, in <module>
NameError: name 'arg' is not defined

Case 4 demonstrates that the scope of the argument variable lies within the function. Case 1 and 3 support that as changes to the arg variable within the function are not reflected in the parameters globally.

But why does Case 2 happen at all? I noticed the same thing when I used append instead of the +=. Shouldn't the changes that happen to arg not have any effect on the variables the function was called with from a different scope?

Any help appreciated. Thanks in advance.

question from:https://stackoverflow.com/questions/65885515/what-is-the-scope-of-argument-variables-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Case 2 is the only one where you use a mutating method on an instance. This affects the parameter passed.

The others do nothing or just reassign the argument. Assignment in python only affects the variable being assigned and not other variables that still refer to the previous instance.

Mandatory link to Ned Batchelder


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...