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,
All calls in Python are "by reference". Integers are immutable in Python. You can't change them.
class C:
def __init__(self, c):
self.c = c
def __call__(self, a, b):
a *= 2
b *= 4
self.c *= 8
return a + b + self.c
A = C(1)
print A(1, 1), A.c
print A(1, 1), A.c
14 8
70 64
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:
>>> def A(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
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.
You can do this if c
is a list:
c = [2]
def A(a, b, c):
a *= 2
b *= 4
c[0] *= 8
return a+b+c[0]
print c # gives [16]