Skip to Content
Python高级编程(第2版)
book

Python高级编程(第2版)

by Posts & Telecom Press, Michał Jaworski, Tarek Ziadé
February 2024
Intermediate to advanced
423 pages
6h 9m
Chinese
Packt Publishing
Content preview from Python高级编程(第2版)

第3章 语法最佳实践——类级别以上

本章我们将重点介绍类的语法最佳实践。这里并不打算涉及设计模式,因为这部分内容将在第14章介绍。本章概述了用于操作和改进类代码的Python高级语法。

在Python 2的历史中,对象模型已经发生了很大变化。在很长一段时间里,同一种语言的面向对象编程范式存在两种实现方式。这两种模型被简称为旧式(old-style)类和新式(new-style)类。Python 3终结了这一分歧,其开发者只能使用被称为新式类的模型。不管怎样,知道两种模型在Python 2中的工作原理仍是很重要的,因为这有助于你移植旧代码和编写向后兼容的应用。了解对象模型如何变化,也有助于你理解它现在为何如此设计。这也是为什么本章包含关于 Python 2 旧特性的大量内容,尽管本书针对的是最新版的Python 3。

本章将讨论下列主题。

  • 子类化内置类型。
  • 访问超类中的方法。
  • 使用property和槽(slot)。
  • 元编程。

Python的子类化内置类型非常简单。有一个叫作object的内置类型,它是所有内置类型的共同祖先,也是所有没有显式指定父类的用户自定义类的共同祖先。正由于此,每当需要实现与某个内置类型具有相似行为的类时,最好的方法就是将这个内置类型子类化。

现在,我们将向你展示一个名为distinctdict类的代码如下,它就使用了这种方法。它是Python中普通的dict类型的子类。这个新类的大部分行为都与普通的dict相同,但它不允许多个键对应相同的值。如果有人试图添加具有相同值的新元素,那么会引发一个ValueError的子类,并给出一些帮助信息:

 class DistinctError(ValueError): """如果向distinctdict添加重复值,则引发这个错误。""" ...
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

Hadoop实际解决方案手册

Hadoop实际解决方案手册

Posts & Telecom Press, JONATHAN OWENS, Lentz Jon, Femiano Brian
TensorFlow机器学习

TensorFlow机器学习

Posts & Telecom Press, Quan Hua, Shams Ul Azeem, Saif Ahmed
Python和NLTK实现自然语言处理

Python和NLTK实现自然语言处理

Posts & Telecom Press, Nitin Hardeniya
Kafka权威指南(第2版)

Kafka权威指南(第2版)

Gwen Shapira, Todd Palino, Rajini Sivaram, Krit Petty

Publisher Resources

ISBN: 9781835887745