call-by-reference function parameters

后端 未结 4 1092
挽巷
挽巷 2021-01-15 02:03

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,

4条回答
  •  梦谈多话
    2021-01-15 02:22

    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
    

提交回复
热议问题