简体   繁体   中英

Python: how to pass a reference to a function

IMO python is pass by value if the parameter is basic types, like number, boolean

func_a(bool_value):
    bool_value = True

Will not change the outside bool_value , right?

So my question is how can I make the bool_value change takes effect in the outside one(pass by reference?

You can use a list to enclose the inout variable:

def func(container):
    container[0] = True


container = [False]
func(container)
print container[0]

The call-by-value/call-by-reference misnomer is an old debate. Python's semantics are more accurately described by CLU's call-by-sharing. See Fredrik Lundh's write up of this for more detail:

Python (always), like Java (mostly) passes arguments (and, in simple assignment, binds names) by object reference . There is no concept of "pass by value", neither does any concept of "reference to a variables" -- only reference to a value (some express this by saying that Python doesn't have "variables"... it has names , which get bound to values -- and that is all that can ever happen).

Mutable objects can have mutating methods (some of which look like operators or even assignment, eg ab = c actually means type(a).__setattr__(a, 'b', c) , which calls a method which may likely be a mutating ones).

But simple assignment to a barename (and argument passing, which is exactly the same as simple assignment to a barename) never has anything at all to do with any mutating methods.

Quite independently of the types involved, simple barename assignment (and, identically, argument passing) only ever binds or rebinds the specific name on the left of the = , never affecting any other name nor any object in any way whatsoever. You're very mistaken if you believe that types have anything to do with the semantics of argument passing (or, identically, simple assignment to barenames).

Unmutable types can't, but if you send a user-defined class instance, a list or a dictionary, you can change it and keep with only one object.

Like this:

def add1(my_list):
    my_list.append(1)

a = []
add1(a)
print a

But, if you do my_list = [1], you obtain a new instance, losing the original reference inside the function, that's why you can't just do "my_bool = False" and hope that outside of the function your variable get that False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM