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版)
294
11
11.10
 
Python
私有属性和
受保护
的属性
Python
不能像
Java
那样使用
private
修饰符创建私有属性,但是它有一个简单的机制,能
避免子类意外覆盖“私有”属性。
举个例子。有人编写了一个名为
Dog
的类,内部用到了
mood
实例属性,但是没有将其开
放。现在,你创建了
Dog
类的子类
Beagle
。如果你在毫不知情的情况下又创建了名为
mood
的实例属性,那么在继承的方法中就会把
Dog
类的
mood
属性覆盖。这是难以调试的问题。
为了避免这种情况,如果以
__mood
的形式(两个前导下划线,尾部没有或最多有一个下划
线)命名实例属性,那么
Python
就会把属性名存入实例属性
__dict__
中,而且会在前面
加上一个下划线和类名。因此,对
Dog
类来说,
__mood
会变成
_Dog__mood
;对
Beagle
来说,
__mood
会变成
_Beagle__mood
。这个语言功能叫
名称改写
name mangling
)。
示例
1
1-12
以示例
11-7
中定义的
Vector2d
类为例对名称改写进行了说明。
示例
11-12
私有属性的名称会被“改写”
,在前面加上
_
和类名
>>> v1 = Vector2d(3, 4)
>>> v1.__dict__
{'_Vector2d__y': 4.0, '_Vector2d__x': 3.0}
>>> v1._Vector2d__x
3.0
名称改写是一种安全措施,不能保证万无一失:它的目的是避免意外访问,不能防止故意
做错事。图
1
1-1
也是一种保护装置。 ...
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