def modify_list(L):
"""Modify the content of a list.
Args:
L: list, len(L) should >= 1
"""
L[0] = 1
L.append(2)
L += [3] # += will not create new object
L = L + [4]
def unitest_modify_list():
L = [0]
modify_list(L)
print(L)
if __name__ == "__main__":
unitest_modify_list()
# results:
[1, 2, 3]
import time
from threading import Thread
def pass_pointer(P):
"""Treat `P` as a pointer.
Args:
P: list, len(P) should >= 1
"""
while True:
time.sleep(1)
print(P)
def modify_pointer_content(P):
t = Thread(target=pass_pointer, args=(P,))
t.setDaemon(True)
t.start()
time.sleep(2.1)
P[0] = 1
time.sleep(2.1)
def unitest_pointer():
P = [0]
modify_pointer_content(P)
if __name__ == "__main__":
unitest_pointer()
[0]
[0]
[1]
[1]
import time
from threading import Thread
from multiprocessing import Process
def pass_pointer(P):
"""Treat `P` as a pointer.
Args:
P: list, len(P) should >= 1
"""
while True:
time.sleep(1)
print(P)
def modify_pointer_content(P):
# t = Thread(target=pass_pointer, args=(P,))
t = Process(target=pass_pointer, args=(P,))
# t.setDaemon(True)
t.daemon = True
t.start()
time.sleep(2.1)
P[0] = 1
time.sleep(2.1)
def unitest_pointer():
P = [0]
modify_pointer_content(P)
if __name__ == "__main__":
unitest_pointer()
[0]
[0]
[0]
[0]
Q: 除了 list 之外, 利用其它可变对象能否实现传引用/指针的功能
Q: += 与 + 的区别