V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
mune
V2EX  ›  Python

小白求教,关于深拷贝中的一个字符串:

  •  
  •   mune · Dec 9, 2017 · 2864 views
    This topic created in 3061 days ago, the information mentioned may be changed or developed.
    >>> from copy import deepcopy
    >>> a=['hello',[1,2,3]]
    >>> b=deepcopy(a)
    >>> [id(x) for x in a]
    [55792504, 55645000]
    >>> [id(x) for x in b]
    [55792504, 58338824]
    >>> a[0]='world'
    >>> a[1].append(4)
    >>>
    >>> print(a)
    ['world', [1, 2, 3, 4]]
    >>> print(b)
    ['hello', [1, 2, 3]]

    这段代码中为啥‘ hello ’的地址是一样的?
    6 replies    2017-12-09 18:13:33 +08:00
    hcnhcn012
        1
    hcnhcn012  
       Dec 9, 2017 via iPhone
    flyico
        2
    flyico  
       Dec 9, 2017   ❤️ 1
    string 属于不可变对象,没必要真给你弄两个一模一样的 string 出来,算是解释器的优化吧
    feihuaxx010
        3
    feihuaxx010  
       Dec 9, 2017 via Android
    你在试试 1-127 的整数
    zhusimaji
        4
    zhusimaji  
       Dec 9, 2017   ❤️ 1
    二楼的解释基本上回答了,一般需要进行深拷贝是怕引用机制改变了原对象。如果是不可变对象那也没操作的必要,所以像 list 这些可变类型必要的时候会进行深拷贝,这些在 fluent python 都有介绍,哈哈
    akiakiseofficial
        5
    akiakiseofficial  
       Dec 9, 2017 via Android
    楼上+1,我也记得 fluent python 中提了一下这个问题。
    ballshapesdsd
        6
    ballshapesdsd  
       Dec 9, 2017
    @zhusimaji thank you sir
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   949 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 21:45 · PVG 05:45 · LAX 14:45 · JFK 17:45
    ♥ Do have faith in what you're doing.