call-by-reference function parameters

后端 未结 4 1053
挽巷
挽巷 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:18

    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
    

    Example

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

    Output

    14 8
    70 64
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-15 02:41

    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]
    
    0 讨论(0)
提交回复
热议问题