def try_to_change_string_reference(the_string):print('got', the_string)the_string = 'In a kingdom by the sea'print('set to', the_string)
outer_string = 'It was many and many a year ago'
print('before, outer_string =', outer_string)try_to_change_string_reference(outer_string)print('after, outer_string =', outer_string)
输出:
before, outer_string = It was many and many a year agogot It was many and many a year agoset to In a kingdom by the seaafter, outer_string = It was many and many a year ago
def return_a_whole_new_string(the_string):new_string = something_to_do_with_the_old_string(the_string)return new_string
# then you could call it likemy_string = return_a_whole_new_string(my_string)
def use_a_wrapper_to_simulate_pass_by_reference(stuff_to_change):new_string = something_to_do_with_the_old_string(stuff_to_change[0])stuff_to_change[0] = new_string
# then you could call it likewrapper = [my_string]use_a_wrapper_to_simulate_pass_by_reference(wrapper)
do_something_with(wrapper[0])
x = [ 2, 4, 4, 5, 5 ]print x # 2, 4, 4, 5, 5
def go( li ) :li = [ 5, 6, 7, 8 ] # re-assigning what li POINTS TO, does not# change the value of the ORIGINAL variable x
go( x )print x # 2, 4, 4, 5, 5 [ STILL! ]
raw_input( 'press any key to continue' )
>>> def x(y):... global z... z = y...
>>> x<function x at 0x00000000020E1730>>>> yTraceback (most recent call last):File "<stdin>", line 1, in <module>NameError: name 'y' is not defined>>> zTraceback (most recent call last):File "<stdin>", line 1, in <module>NameError: name 'z' is not defined
>>> x(2)>>> x<function x at 0x00000000020E1730>>>> yTraceback (most recent call last):File "<stdin>", line 1, in <module>NameError: name 'y' is not defined>>> z2
def test(l):print "Received", l , id(l)l = [0, 0, 0]print "Changed to", l, id(l) # New local object created, breaking link to global l
l= [1,2,3]print "Original", l, id(l)test(l)print "After", l, id(l)
提供:
Original [1, 2, 3] 4454645632Received [1, 2, 3] 4454645632Changed to [0, 0, 0] 4474591928After [1, 2, 3] 4454645632
class ByRef:def __init__(self, r, w, d):self._read = rself._write = wself._delete = ddef set(self, val):self._write(val)def get(self):return self._read()def remove(self):self._delete()wrapped = property(get, set, remove)
# left as an exercise for the reader: define set, get, remove as local functions using global / nonlocalr = ByRef(get, set, remove)r.wrapped = 15
class RefsObj(object):"A class which helps to create references to variables."pass
...
# an example of usagedef change_ref_var(ref_obj):ref_obj.val = 24
ref_obj = RefsObj()ref_obj.val = 1print(ref_obj.val) # or print ref_obj.val for python2change_ref_var(ref_obj)print(ref_obj.val)
# returns the result of adding numbers `a` and `b`def AddNumbers(a, b, ref): # using a dict for referenceresult = a + bref['multi'] = a * b # reference the multi. ref['multi'] is numberref['msg'] = "The result: " + str(result) + " was nice!"return result
number1 = 5number2 = 10ref = {} # init a dict like that so it can save all the referenced values. this is because all dictionaries are passed by reference, while strings and numbers do not.
sum = AddNumbers(number1, number2, ref)print("sum: ", sum) # the returned valueprint("multi: ", ref['multi']) # a referenced valueprint("msg: ", ref['msg']) # a referenced value
def need_to_modify(update):update(42) # set new value 42# other code
def call_it():value = 21def update_value(new_value):nonlocal valuevalue = new_valueneed_to_modify(update_value)print(value) # prints 42
def somefunction(a, b, c):a = a * 2b = b + ac = a * b * creturn a, b, c
x = 3y = 5z = 10print(F"Before : {x}, {y}, {z}")
x, y, z = somefunction(x, y, z)
print(F"After : {x}, {y}, {z}")
from dataclasses import dataclass
@dataclassclass Holder:obj: your_type # Need any type? Use "obj: object" then.
def foo(ref: Holder):ref.obj = do_something()