问题
传值还是传址是Python程序设计中最容易混淆和出错的一类编程方式。
方法
传值
''' (1) 数字 ''' a = 1 def foo1(a): a = 10 foo1(a) print(f'a = {a}') # 1 ''' (2) 字符串 ''' b = 'hello' def foo2(b): b = 'world' foo2(b) print(f'b = {b}') # hello ''' (3) 元组 ''' c = (1,2,3) def foo3(c): c = (4,5,6) foo3(c) print(f'c = {c}') # (1, 2, 3)
传址
''' (1) 列表 ''' a = [1,2,3] def foo1(a): a[0] = 5 a[1] = 5 a[2] = 5 foo1(a) print(f'a = {a}') # a = [5, 5, 5] ''' (2) 字典 ''' b = {'name':'chen'} def foo2(b): b['name'] = 'zhen' foo2(b) print(f'b = {b}') # b = {'name': 'zhen'} ''' (3) 对象 ''' class User: def __init(self): self.username = 'chen' def foo4(user): user.username = 'zhen' u = User() foo4(u) print(f'user = {u.username}') # user = zhen
结语
数字、字符串、元组是传值;
列表、字典是传址。