python浅拷贝不改变id 地址

主要想知道 为啥 浅拷贝对不可变数据类型 不改变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 []

元组 这边没有 重新 生成新的(😀)

为什么元组 不生成新的呢 ?

我觉的元组本身就是不可变的 引用就好 不用担心值变动何必浪费资源

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值