主要想知道 为啥 浅拷贝对不可变数据类型 不改变id 地址
上代码
def copy(x):
"""Shallow copy operation on arbitrary Python objects.
See the module's __doc__ string for more info.
"""
cls = type(x)
copier = _copy_dispatch.get(cls)
print(_copy_dispatch)
if copier:
return copier(x)
......
代码输出可以看出 数据类型作为键,值是一个function 如果字典中有数据类型的key 调用方法
{<class 'NoneType'>: <function _copy_immutable at 0x7f378d404a60>, <class 'int'>: <function _copy_immutable at 0x7f378d404a60>, .... <class 'bytearray'>: <method 'copy' of 'bytearray' objects>}
继续
_copy_dispatch = d = {}
def _copy_immutable(x):
return x
for t in (type(None), int, float, bool, complex, str, tuple,
bytes, frozenset, type, range, slice,
types.BuiltinFunctionType, type(Ellipsis), type(NotImplemented),
types.FunctionType, weakref.ref):
d[t] = _copy_immutable
t = getattr(types, "CodeType", None)
if t is not None:
d[t] = _copy_immutable
d[list] = list.copy
d[dict] = dict.copy
d[set] = set.copy
d[bytearray] = bytearray.copy
上面的function 就是 _copy_immutable 方法 return 参数
为什么 像元组这些不可变类型 id不会变呢 因为
d[list] = list.copy
d[dict] = dict.copy
d[set] = set.copy
d[bytearray] = bytearray.copy
例如 list.copy 重新生成一个新的 所以id变了
def copy(self): # real signature unknown; restored from __doc__
""" L.copy() -> list -- a shallow copy of L """
return []
元组 这边没有 重新 生成新的(😀)
为什么元组 不生成新的呢 ?
我觉的元组本身就是不可变的 引用就好 不用担心值变动何必浪费资源