Pascal "var parameter" in 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 function? Can I change the string parameter inside the method or use return and assign this variable later?

+4
source share
4 answers

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

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

Thus, your simple example can be translated into Python as follows:

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

An alternative is to transfer to mutable objects (dictionaries, lists, etc.) and change their contents.

+5
source

This is called pass-by-reference, and no, Python doesn’t (though if you pass a mutable object by value and change it in a function, it has changed everywhere because it is the same object.)

+4
source

It is better to do it differently in Python, see other answers.

If you need to pass something by reference, a simple trick gives it a list containing only 1 element, and allows the function to modify listarg[0] .

+1
source

If you absolutely need to, you can do something like this:

 class ValueHolder(object): def __init__(self, value): self.value = value def a(s1, s2): s1.value += 'test' + s1.value s2.value = '{}({})'.format(s1.value, s2.value) s1 = ValueHolder('spam') s2 = ValueHolder('eggs') a(s1, s2) print s1.value, s2.value 

But this is a pretty ugly way to do this.

It would be better

  • function that returns changed values

     def a(s1, s2): return s1 + 'test' + s1, s2 + 'aaa' 
  • or a class that contains old and new data.

     class StringModifier(object) def __init__(self, s1, s2): self.s1 = s1 self.s2 = s2 def a(self): self.s1 += 'test' + self.s1 self.s2 = '{}({})'.format(self.s1, self.s2) sm = StringModifier('spam', 'eggs') sm.a() print sm.s1, sm.s2 
0
source

Source: https://habr.com/ru/post/1491410/


All Articles