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版)
700
24
用户可以使用一整个字符串或者产出字符串的可迭代对象提供字段名称。
接受的参数与
collections.namedtuple
的前两个参数类似,返回一个
type
,即一个行
为类似元组的类。
使用属性名构建一个元组,这将成为新建类的
__slots__
属性的值。
这个函数将成为新建类的
__init__
方法,接受位置参数和关键字参数。
3
按照
__slots__
设定的顺序产出字段值。
迭代
__slots__
self
,生成友好的字符串表示形式。
组建类属性字典。
调用
type
构造函数,构建新类,然后将其返回。
把以空格或逗号分隔的
names
转换成字符串列表。
示例
24-2
是我们第一次在类型提示中见到
type
。如果只使用
-> type
注解,则表示
record_
factory
会返回一个类——这也没错。但是,
-> type[tuple]
注解更准确,它指明了返回的
类是
tuple
的子类。
在示例
24-2
中,
record_factory
函数的最后一行构建了一个类,类的名称是
cls_name
值,唯一的直接基类是
object
,而且在命名空间中加载了
__slots__
__init__
__iter__
__repr__
,其中后
3
个是实例方法。
我们本可以把
__slots__
类属性的名称改成其他值,但是如果那样做,则必须实现
__setattr__
方法,以验证在为属性赋值时属性的名称,因为对于这种记录类,我们希望属性始终是固
定的那几个,而且顺序相同。然而
11
.11
节说过,
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