Skip to Content
流畅的Python(第2版)
book

流畅的Python(第2版)

by Luciano Ramalho
April 2023
Intermediate to advanced
769 pages
25h 16m
Chinese
Posts & Telecom Press
Content preview from 流畅的Python(第2版)
对象引用、可变性和垃圾回收
167
达,从而使得对象被删除。
你可能觉得奇怪,为什么示例
6-16
中的对象
{1, 2, 3}
被销毁了?毕竟,我们把
s1
引用
传给
finalize
函数了,而为了监控对象和调用回调,必须要有引用。这是因为,
finalize
持有
{1, 2, 3}
弱引用
weak reference
)。对象的弱引用不增加对象的引用计数。因此,
弱引用不阻碍目标对象被当作垃圾而回收。弱引用在缓存应用中用得到,因为我们不希望
由于存在对缓存的引用而导致缓存的对象无法被删除。
6.7
 
Python
对不可变类型施加的把戏
你可以放心地跳过本节。这里讨论的是
Python
的实现细节,对
Python
用户
来说没那么重要,可能也不适用于
Python
的其他实现甚至
CPython
的未来版
本。尽管如此,但我见过有人遇到极端情况时错误地使用
is
运算符,因此
还是有必要讲一下。
我惊讶地发现,对元组
t
来说,
t[:]
不创建副本,而是返回同一个对象的引用。此外,
tuple(t)
获得的也是同一个元组的引用。
3
示例
6-17
可以证明这一点。
示例
6-17
使用一个元组构建一个元组,得到的其实是同一个元组
>>> t1 = (1, 2, 3)
>>> t2 = tuple(t1)
>>> t2 is t1
True
>>> t3 = t1[:]
>>> t3 is t1
True
t1
t2
绑定同一个对象。
t3
也是。
str
bytes
frozenset
实例也有这种行为。注意,
frozenset
对象不是序列,因此 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Python高级编程(第2版)

Python高级编程(第2版)

Posts & Telecom Press, Michał Jaworski, Tarek Ziadé
Python贝叶斯分析(第2版)

Python贝叶斯分析(第2版)

Posts & Telecom Press, Osvaldo Martin
高效能PYTHON程式設計

高效能PYTHON程式設計

Micha Gorelick, Ian Ozsvald

Publisher Resources

ISBN: 9787115612366