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版)
符合
Python
风格的对象
299
11.12
 覆盖类属性
Python
有一个很独特的功能:类属性可为实例属性提供默认值。
Vector2d
中有一个名为
typecode
的类属性。
__bytes__
方法两次用到了这个属性,而且都故意使用
self.typecode
读取它的值。因为
Vector2d
实例本身没有
typecode
属性,所以
self.typecode
默认获取的
Vector2d.typecode
类属性的值。
但是,如果为不存在的实例属性赋值,那么将创建一个新实例属性。假如为
typecode
实例
属性赋值,那么同名类属性将不受影响。然而,一旦这样做,实例读取的
self.typecode
是实例属性
typecode
,也就是把同名类属性遮盖了。借助这个功能,可以为各个实例的
typecode
属性定制不同的值。
Vector2d.typecode
属性的默认值是
'd'
,即转换成字节序列时使用
8
字节双精度浮点数表
示向量的各个分量。如果在转换之前把
Vector2d
实例的
typecode
属性设为
'f'
,那么将使
4
字节单精度浮点数表示各个分量,如示例
1
1-18
所示。
示例
11-18
设定原本从类中继承的
typecode
属性,自定义一个实例属性
>>> from vector2d_v3 import Vector2d
>>> v1 = Vector2d(1.1, 2.2)
>>> dumpd = bytes(v1)
>>> dumpd
b'd\x9a\x99\x99\x99\x99\x99\xf1?\x9a\x99\x99\x99\x99\x99\x01@' ...
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.
Start your free trial

You might also like

Python高级编程(第2版)

Python高级编程(第2版)

Posts & Telecom Press, Michał Jaworski, Tarek Ziadé
Kafka权威指南(第2版)

Kafka权威指南(第2版)

Gwen Shapira, Todd Palino, Rajini Sivaram, Krit Petty
Python贝叶斯分析(第2版)

Python贝叶斯分析(第2版)

Posts & Telecom Press, Osvaldo Martin

Publisher Resources

ISBN: 9787115612366