Skip to content Skip to sidebar Skip to footer

Call-by-reference Function Parameters

Given a function: def A(a, b, c): a *= 2 b *= 4 c *= 8 return a+b+c How can I set the 'c' var to be called-by-reference, so if i call d = A(a,b,c), c will point to

Solution 1:

You're getting into murky territory: you're talking about declaring global (or nonlocal) variables in functions, which should simply not be done. Functions are meant to do one thing, and do them without the consent of other values or functions affecting their state or output.

It's difficult to suggest a working example: are you alright with having copies of the variables left behind for later reference? You could expand this code to pass back a tuple, and reference the members of the tuple if needed, or the sum:

>>>defA(a, b, c):
        return (a*2, b*4, c*8)

>>>d = A(2, 4, 8)>>>sum(d)
84
>>>d[-1] #or whatever index you'd need...this may serve best as a constant
64

Solution 2:

You can do this if c is a list:

c=[2]
def A(a, b,c):
    a *=2
    b *=4c[0]*=8return a+b+c[0]
print c# gives [16]

Solution 3:

You can't. Python cannot do that.

What you can do is pass a wrapper that has __imul__() defined and an embedded int, and the augmented assignment will result in the embedded attribute being mutated instead.

Solution 4:

All calls in Python are "by reference". Integers are immutable in Python. You can't change them.

classC:def__init__(self, c):
       self.c = c
   def__call__(self, a, b):
       a *= 2
       b *= 4self.c *= 8return a + b + self.c

Example

A = C(1)
print A(1, 1), A.c
print A(1, 1), A.c

Output

14 8
70 64

Post a Comment for "Call-by-reference Function Parameters"