·对象与应用
列表
In [1]: a = [1,2,3]
In [2]: b = a # a,b同个引用地址
In [3]: a.append(3)
In [4]: a,b
Out[4]: ([1, 2, 3, 3], [1, 2, 3, 3])
字典
In [5]: c = {1:2}
In [6]: d = c # a,b同个引用地址
In [7]: c[2] = 3
In [8]: c, d
Out[8]: ({1: 2, 2: 3}, {1: 2, 2: 3})
列表操作对象
extend
+=
= +
In [9]: a = [1, 2]
In [10]: id(a)
Out[10]: 2541550349000
In [11]: a.extend([3])
In [12]: id(a)
Out[12]: 2541550349000
In [13]: a += [4]
In [14]: id(a)
Out[14]: 2541550349000
In [15]: a = a + [5] # # + 重新开辟了空间,引用改变了
In [16]: id(a)
Out[16]: 2541550119752
In [17]: a
Out[17]: [1, 2, 3, 4, 5]
元组内的列表
In [18]: a = ([], [])
In [19]: a[0].append(1)
In [20]: a[0].extend([2])
In [21]: a[0] += [3] # 这里虽然报错了但还是添加进去了
TypeError Traceback (most recent call last)
in ()
—-> 1 a[0] +=[3]
TypeError: ‘tuple’ object does not support item assignment
In [22]: a
Out[22]: ([1, 2, 3], [])
复制对象的deepcopy和[:]
In [20]: from copy import deepcopy
In [21]: a = [1, 2, 3]
In [22]: b = deepcopy(a)
In [23]: b.append(4)
In [24]: id(a)
Out[24]: 1986228666632
In [25]: id(a), id(b),a, b
Out[25]: (1986228666632, 1986226832648, [1, 2, 3], [1, 2, 3, 4])
In [26]: c = a[:] # 开辟了空间,改变了地址,不是应用
In [27]: id(a), id(b),id(c)
Out[27]: (1986228666632, 1986226832648, 1986228195080)
copy 赋值了 一层 第二层改变,也跟着改变 , deepcopy 复制了两层
·函数参数初始值
In [28]: def a(b=[]):
…: b.append(“hi”)
…: print(b)
…:
In [29]: a()
[‘hi’]
In [30]: a()
[‘hi’, ‘hi’]
In [31]: a([“2”])
[‘2’, ‘hi’]
In [32]: a()
[‘hi’, ‘hi’, ‘hi’]
- 类属性
In [33]: class A:
…: b = []
…: def init(self, c):
…: self.b.append(c)
…:
In [34]: f = A(1)
In [35]: g = A(2)
In [36]: f.b, g.b
Out[36]: ([1, 2], [1, 2])
·闭包
我们经常这样用
In [1]: def wrap(log):
…: thno = [0]
…: def initfunc():
…: thno[0] +=1
…: log.info(“Thread-%s” % thno[0])
…: return thno[0]
…: return initfunc
…:
但是在多线程的时候, 它会产生点意外
在多个线程可能获得相同的thno[0]值
另一个情况…..循环生成闭包
In [5]: a = []
In [6]: for i in range(10):
…: def b():
…: return i
…: a.append(b)
…:
In [7]: a0
Out[7]: 9
In [8]: a1
Out[8]: 9
In [9]: a9
Out[9]: 9
In [15]: a = []
In [16]: def bwrap(i):
…: def b():
…: return i
…: return b
…: for i in range(10):
…: a.append(bwrap(i))
…:
In [17]: a0
Out[17]: 0
In [18]: a8
Out[18]: 8
·原因是….
- 函数层面保存变量
- 在多线程时,
外层函数保存的变量
成为各个线程的 “全局变量”
GIL下CPU 使用超过100%
·其实是逃出了GIL的魔掌
·走进了C的怀抱