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版)
符合
Python
风格的对象
289
现在,向量不会被意外修改,有了一定的安全性,接下来可以实现
__hash__
方法了。这
个方法应该返回一个
int
值,理想情况下还要考虑对象属性的哈希值(
__eq__
方法也是如
此),因为相等的对象应该具有相同的哈希值。特殊方法
__hash__
的文档建议根据元组的
分量计算哈希值,如示例
1
1-8
所示。
示例
11-8
vector2d_v3.py
:实现
__hash__
方法
# Vector2d类中定义
def __hash__(self):
return hash((self.x, self.y))
实现
__hash__
方法之后,向量就变成可哈希的了。
>>> v1 = Vector2d(3, 4)
>>> v2 = Vector2d(3.1, 4.2)
>>> hash(v1), hash(v2)
(1079245023883434373, 1994163070182233067)
>>> {v1, v2}
{Vector2d(3.1, 4.2), Vector2d(3.0, 4.0)}
为了创建可哈希的类型,不一定要实现特性,也不一定要保护实例属性,正
确实现
__hash__
方法和
__eq__
方法即可。但是,可哈希对象的值绝不应该
变化,因此我们借机提到了只读特性。
如果你定义的类型有标量数值,那么可能还要实现
__int__
方法和
__float__
方法(分别被
int()
构造函数和
float()
构造函数调用),以便在某些情况下强制转换类型。此外,还有
用于支持内置构造函数 ...
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