Python中的Pascal"var参数"

Pro*_*020 4 python

在Pascal中我们有var参数,函数可以将参数值更改为新值:

procedure a(var S1, S2: string);
begin
  S1:= S1+'test'+S1;
  S2:= S1+'('+S2+')';
end;
Run Code Online (Sandbox Code Playgroud)

Python有这样的功能吗?我可以更改string方法内的参数,还是必须return稍后使用并分配变量?

Mar*_*ers 5

Python可以返回多个值(以元组的形式),废弃了通过引用传递值的需要.

在您的简单示例中,即使您能够应用相同的技术,也无法实现与Python字符串不可变相同的结果.

因此,您的简单示例可以转换为Python:

def a(s1, s2):
    s1 = '{0}test{0}'.format(s1)
    s2 = '{}({})'.format(s1, s2)
    return s1, s2

foo, bar = a(foo, bar)
Run Code Online (Sandbox Code Playgroud)

另一种方法是传入可变对象(字典,列表等)并改变其内容.