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 版

第 38 章 托管属性 托管属性

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

本章扩展了前面介绍的属性截取技术,介绍了另一种属性截取技术,并在几个较大的示例中使用了这些技术。与本书这一部分的所有内容一样,本章被列为高级主题和选读内容,因为大多数应用程序编程人员不需要关心这里讨论的材料--他们可以获取和设置对象的属性,而无需关心属性的实现。

特别是对于工具构建者来说,管理属性访问是灵活应用程序接口的重要组成部分。此外,了解这里涉及的描述符模型可以让槽和属性等相关工具变得更加具体,如果它出现在你必须使用的代码中,甚至可能是必读内容。

为什么要管理属性?

在大多数 Python 程序中,对象属性是的核心--我们经常在这里存储脚本处理的实体的信息。通常,属性只是对象的名称;例如,一个人的name 属性可能是一个简单的字符串,可以用基本的属性语法获取和设置:

person.name                 # Fetch attribute value
person.name = value         # Change attribute value

在大多数情况下,属性存在于对象本身,或者从派生类继承而来。这种基本模式足以满足您在 Python 职业生涯中编写的大多数程序。

但有时需要更大的灵活性。假设你编写了一个直接使用name属性的程序,但随后你的需求发生了变化--例如,你决定在设置名称时应使用逻辑验证,或在获取名称时以某种方式更改名称。要管理对属性值的访问(validtransform 在这里是抽象的),只需编写方法即可:

class Person:
    def getName(self):
        if not valid():
            raise TypeError('cannot fetch name')
        else:
            return self.name.transform()

    def setName(self, value):
         if not valid(value):
            raise TypeError('cannot change name')
        else:
            self.name = transform(value)

person = Person()
person.getName()
person.setName('value')

不过,这也要求更改整个程序中所有使用名称的地方--这可能不是一项简单的任务。此外,这种方法还要求程序知道值是如何输出的:是作为简单的名称,还是作为被调用的方法。如果一开始就使用基于方法的数据接口,客户端就不会受到更改的影响;如果不这样做,客户端就会出现问题。

这个问题可能比你想象的要经常出现。例如,在电子表格程序中,单元格的值开始时可能是一个简单的离散值,但后来可能会变成一个任意的计算结果。由于对象的接口应具有足够的灵活性,以便在不破坏现有代码的情况下支持未来的这种变化,因此,以后再切换到方法就不太理想了。

插入代码以便在属性访问时运行

如果需要,更好的解决方案是允许在属性访问时自动运行代码。这正是托管属性的主要作用之一--它们提供了在事后添加属性访问逻辑的方法。更广泛地说,托管属性支持任意的属性使用模式,而不仅仅是简单的数据存储。

在本书的不同章节中,我们曾遇到过一些 Python 工具,它们允许我们的脚本在获取属性值时动态计算属性值,在存储属性值时验证或更改属性值。在本章中,我们将扩展已经介绍过的工具,探索其他可用的工具,并研究该领域中一些较大的用例。具体来说,本章将介绍四种访问器技术:

  • __getattr____setattr__ ...

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