Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pascal "var parameter" in Python

Tags:

python

In Pascal we have var parameters, and functions can change parameter values to new values:

procedure a(var S1, S2: string);
begin
  S1:= S1+'test'+S1;
  S2:= S1+'('+S2+')';
end;

Does Python have such a feature? Can I change the string parameter inside the method, or must I use return and assign the variable later?

like image 618
Prog1020 Avatar asked Dec 26 '22 00:12

Prog1020


1 Answers

Python can return multiple values (in the form of a tuple), obsoleting the need to pass values by reference.

In your simple sample case, even if you were able to apply the same technique, you could not achieve the same result as Python strings are not mutable.

As such, your simple example can be translated to Python as:

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

foo, bar = a(foo, bar)

The alternative is to pass in mutable objects (dictionaries, lists, etc.) and alter their contents.

like image 152
Martijn Pieters Avatar answered Jan 09 '23 09:01

Martijn Pieters