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版)
641
22
动态属性和特性
特性之所以重要,是因为它的存在使得开发者可以非常安全并且确定可行地将公
共数据属性作为类的公共接口的一部分开放出来。
——
Martelli
Ravenscroft
Holden
“特性的重要性”
1
Python
中,数据属性和方法统称
属性
attribute
)。其实,方法是
可调用
的属性。
动态属
dynamic
attribute
)的接口与数据属性一样(
obj.attr
),不过按需计算。这与
Bertrand
Meyer
所说的
统一访问原则
Uniform Access
Principle
)相符。
不管服务是由存储还是计算实现的,一个模块提供的所有服务应统一表示法。
2
Python
中,实现动态属性的方式有好几种。本章涵盖最简单的方式:
@property
装饰器
__getattr__
特殊方法。
用户定义的类通过
__getattr__
方法可以实现一种我称之为
虚拟属性
virtual attribute
)的
动态属性。虚拟属性在类的源码中没有显式声明,也不出现在实例属性
__dict__
中,但是
我们随时都能访问,而且当用户读取不存在的属性(例如
obj.no_such_attr
)时,还能即
时计算。
创建动态属性和虚拟属性是一种元编程,框架的作者经常这么做。然而,在
Python
中,
关的基础技术十分简单,在日常数据转换任务中也能用到。下面我们以这种任务开启本章
的话题。
1
出自
Python in a Nutshell, 3rd ed.
Alex Martelli
Anna ...
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