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
James369
V2EX  ›  Python

为何 Python3 要搞一个不可变对象的概念?

  •  
  •   James369 · May 6, 2021 · 2534 views
    This topic created in 1821 days ago, the information mentioned may be changed or developed.
    首先,python 在函数传递参数时,都是传递引用(因为无论传入整数 int 还是列表 list,本质都是类对象)。

    那么 int 作为不可变对象我还可以理解,比如下面的行为很正常:

    b1 = 3
    print(id(b1)) #4321884528
    b1 += 4
    print(id(b1)) #4321884656,id 变了,正常。
    b1 = b1 + 4
    print(id(b1)) #4321884784,id 变了,也正常。

    但是,换成可变对象 list,就有点诡异了:

    a1 = [1, 2, 3]
    print(id(a1)) #4358212608
    a1 += ['aa', 'bb']
    print(id(a1)) #4358212608,id 没变,正常
    a1 = a1 + ['aa', 'bb']
    print(id(a1)) #4357527936,id 怎么就变了呢,这有点变得莫名其妙了?

    按正常理解,x += y,应该等同于 x = x + y,这么一搞,这个特性就有点匪夷所思了。
    Supplement 1  ·  May 6, 2021
    经过查阅,发现不可变对象的一些优点,就是可以节省内存。比如:

    a = 12
    b = 12
    a is b #True

    s1 = 'abc'
    s2 = 'abc'
    s1 is s2 # True
    3 replies    2021-05-06 15:25:34 +08:00
    aldslvda
        1
    aldslvda  
       May 6, 2021   ❤️ 4
    += 用的是__iadd__
    + 用的是__add__
    Jirajine
        2
    Jirajine  
       May 6, 2021
    a1 += ['aa', 'bb'] 可以 desugar 成 add_to(a1,['aa','bb']),a1 = a1 + ['aa', 'bb'] 则是 a1 = add(a1,['aa','bb'])
    区别是显而易见的。
    est
        3
    est  
       May 6, 2021
    一楼正解。你可以完全把 + 定义成不变的。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2367 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 04:22 · PVG 12:22 · LAX 21:22 · JFK 00:22
    ♥ Do have faith in what you're doing.