[英]python: how to change the value of function's input parameter?
I tried to modify the value of a string inside a function, like below:我试图修改函数内字符串的值,如下所示:
>>> def appendFlag(target, value):
... target += value
... target += " "
...
>>> appendFlag
<function appendFlag at 0x102933398>
>>> appendFlag(m,"ok")
>>> m
''
Well, seems the "target" is only changed within the function, but how to make the new value viable outside the function?好吧,似乎“目标”只是在函数内改变,但如何使新值在函数外可行? Thanks.
谢谢。
This is handled in python by returning.这是通过返回在python中处理的。
def appendFlag(target, value):
target += value
target += " "
return target
you can use it like this:你可以这样使用它:
m = appendFlag(m,"ok")
you can even return several variables like this:你甚至可以像这样返回几个变量:
def f(a,b):
a += 1
b += 1
return a,b
and use it like this:并像这样使用它:
a,b = f(4,5)
You need to use an object that can be modified您需要使用可以修改的对象
>>> m = []
>>> def appendFlag(target, value):
... target.append(value)
... target.append(" ")
...
>>> appendFlag(m, "ok")
>>> m
['ok', ' ']
I tried to modify the value of a string inside a function, like below:我试图修改函数中字符串的值,如下所示:
>>> def appendFlag(target, value):
... target += value
... target += " "
...
>>> appendFlag
<function appendFlag at 0x102933398>
>>> appendFlag(m,"ok")
>>> m
''
Well, seems the "target" is only changed within the function, but how to make the new value viable outside the function?好吧,似乎“目标”仅在函数内更改,但是如何使新值在函数外可行? Thanks.
谢谢。
The variables inside the function has got only function scope, if you change the value of the variable from inside the function it wont get reflected outside the function.函数内部的变量只有函数作用域,如果你从函数内部改变变量的值,它不会在函数外部得到反映。 If you want to change the value of the global variable m, update it from outside the function as follows
如果要更改全局变量 m 的值,请从函数外部更新它,如下所示
def appendFlag(target, value):
target += value
target += " "
return target
m=''
m=appendFlag(m,'ok')
Mutable data types, such as lists or dictionaries, can be changed from within the function without returning:可变数据类型,例如列表或字典,可以在函数内更改而无需返回:
def duplicate_last(l):
l.append(l[-1])
l = [1, 2, 3]
duplicate_last(l)
The reason for that is different memory management for mutable and immutable objects in python.原因是python中可变和不可变对象的内存管理不同。
Your function needs to return the new value.您的函数需要返回新值。 The
target
variable only has scope within the appendFlag
function. target
变量仅在appendFlag
函数内具有作用域。
def appendFlag(target, value):
...
return target
m = appendFlag(m, "ok")
Make a new class and set the target as the member of class.创建一个新类并将目标设置为类的成员。 Then try setattr(class, 'target', value).
然后尝试 setattr(class, 'target', value)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.