Skip to Content
《学习 Python》第 5 版
book

《学习 Python》第 5 版

by Mark Lutz
May 2025
Intermediate to advanced
1648 pages
23h 5m
Chinese
O'Reilly Media, Inc.
Content preview from 《学习 Python》第 5 版

第 31 章 使用类进行设计 使用类进行设计

本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com

到目前为止,在本书的这一部分,我们主要讨论了如何使用 Python 的 OOP 工具--类。但 OOP 也涉及设计问题,即如何使用类来建模有用的对象。本章将涉及一些 OOP 的核心思想,并介绍一些比迄今为止所展示的更现实的例子。

在学习过程中,我们将用 Python 编写一些常见的 OOP 设计模式,如继承、组合、委托和工厂。我们还将研究一些注重设计的类概念,如伪私有属性、多重继承和绑定方法。

首先要说明的是:这里提到的一些设计术语需要更多的解释,我无法在本书中提供。如果这些材料激发了你的好奇心,我建议你下一步先去阅读有关 OOP 设计或设计模式的文章。正如我们将看到的,好消息是 Python 使许多传统的设计模式变得微不足道。

Python 和 OOP

让我们先来回顾一下-Python 对 OOP 的实现可以用三个观点来概括:

继承

在 Python 中,继承是基于属性查找的(在X.name 表达式中)。

多态性

X.method 中,,method的含义取决于主客体的类型(类别)X

封装

方法和运算符实现行为,尽管数据隐藏是默认的惯例。

现在,您应该对 Python 中的继承有了很好的了解。我们已经多次讨论过 Python 的多态性;它源于 Python 的无类型声明。因为属性总是在运行时解析,所以实现相同接口的对象可以自动互换;客户不需要知道他们调用的方法是由哪种对象实现的。

封装在 Python 中的意思是打包,即把实现细节隐藏在对象的接口后面。它并不意味着强制隐私,尽管这可以通过代码来实现,我们将在第 39 章中看到。尽管如此,封装在 Python 中还是可用和有用的:它允许改变对象接口的实现而不影响该对象的用户。

多态意味着接口,而不是调用签名

一些 OOP 语言也将多态性定义为根据参数的类型签名--传递的数量和/或参数的类型--重载函数。因为 Python 中没有类型声明,所以这个概念并不适用;正如我们所看到的,Python 中的多态性是基于对象接口的,而不是基于类型的。

如果你怀念 C++ 时代,可以尝试通过参数列表来重载方法,就像这样:

class C:
    def meth(self, x):
        ...
    def meth(self, x, y, z):
        ...

这段代码会运行,但由于def 只是将一个对象赋值给类作用域中的一个名称,因此方法函数的最后一个定义是唯一会被保留的定义。换句话说,就好比你说X = 1 ,然后说X = 2X 就会变成2 。因此,一个方法名只能有一个定义。

如果确实需要,可以使用第 4 章第 9 章中介绍的类型测试思想或 18 章中介绍的参数列表工具,编写基于类型的选择代码:

class C:
    def meth(self, *args):
        if len(args) == 1:              # Branch on number arguments
            ...
        elif type(arg[0]) == int:       # Branch on argument types (or isinstance())
            ...

但您通常不应该这样做--这不是 Python 的方式。正如第 16 章所述,您应该在编写代码时只期待对象接口,而不是特定的数据类型。这样,无论是现在还是将来,它都会对更广泛的类型和应用程序有用:

class C:
    def meth(self, x):
        x.operation()                   # Assume x ...
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

学习 Java,第 6 版

学习 Java,第 6 版

Marc Loy, Patrick Niemeyer, Daniel Leuck
《高性能 Python》第二版

《高性能 Python》第二版

Micha Gorelick, Ian Ozsvald

Publisher Resources

ISBN: 9798341656963