可以看一下往期文章。
这里还是以 python 为例
引用类型通过参数传递改变
dict
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| order = { "order": { "order": 1 } }
def set_order1(order): order["order"] = 2
def set_order2(order): order["order"] = 3
if __name__ == '__main__': order = order.get("order") set_order1(order) print(order) set_order2(order) print(order)
|
输出
1 2
| {'order': 2} {'order': 3}
|
list
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| order = [ 1, 2, 3 ]
def set_order1(order): order[0] = 2
def set_order2(order): order[0] = 3
if __name__ == '__main__': set_order1(order) print(order) set_order2(order) print(order)
|
引用类型传参,参数的变化情况
传参有两种情况,注意下面的区分
方式一
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| import time import threading import random
order = { "order": { "order": 1 } }
def set_order1(order): while 1: print(order.get("order")) time.sleep(3)
def set_order2(order): while 1: order["order"] = random.randint(1, 100) print(f"修改 {order.get('order')}") time.sleep(3)
if __name__ == '__main__': order = order.get("order") t1 = threading.Thread(target=set_order1, args=(order,)) t2 = threading.Thread(target=set_order2, args=(order,)) t1.start() t2.start() t1.join() t2.join()
|
输出
1 2 3 4 5 6 7 8
| 1 修改 26 26 修改 39 39 修改 14 14 修改 30
|
方式二
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| import time import threading import random
order = { "order": { "order": 1 } }
def set_order1(order): while 1: print(order) time.sleep(3)
def set_order2(order): while 1: order["order"] = random.randint(1, 100) print(f"修改 {order.get('order')}") time.sleep(3)
if __name__ == '__main__': order = order.get("order") t1 = threading.Thread(target=set_order1, args=(order.get("order"),)) t2 = threading.Thread(target=set_order2, args=(order,)) t1.start() t2.start() t1.join() t2.join()
|
输出
1 2 3 4 5 6 7 8
| 1 修改 15 1 修改 17 1 修改 91 1 修改 73
|
上面的第二种方式,如果传的是引导参数的最后的值,是不会跟着变化的,程序中用 int
举例,实际上,将 int
换成你自定义的 class
结果表现都是一样的。