知识卡片
元组工厂仍须验证字段定义
示范named_tuple用tuple子类保存值,按字段索引装property,并以new检查实参数量,展示声明生成类型。
结构图:
classDiagram
tuple <|-- Point
class Point {
+__new__(*args)
}
class named_tuple {
<<函数工厂非类型>>
}
named_tuple ..> Point : 构造类型并安装字段访问器
它不是标准namedtuple的等价实现:需验证字段名与冲突,且未设空slots时仍可能有实例字典;元组元素不可重赋不等于整个对象无额外状态。
把同类访问器安装工作移到元类初始化,可在每个派生类定义时完成;不可变元组内容仍应在实例new阶段创建。字段名冲突、重复和额外实例字典等限制并未因此自动消除。
这张卡片看不懂?
这张卡片的反馈已满 10 条,暂时无法继续提交。
已有反馈 · 0 / 10 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 2 处
- · 查看原书依据
def named_tuple(classname, fieldnames): # Populate a dictionary of field property accessors cls_dict = { name: property(operator.itemge
- · 查看原书依据
property(operator.itemgetter(n))) class StructTuple(tuple, metaclass=StructTupleMeta): _fields = [] def __new__(cls, *args): if len(arg
参考来源
- 位置:《Python Cookbook(第3版)中文版》9.18 通过编程的方式来定义类(spine17;extracted/Python Cookbook(第3版)中文版/_epub-src/OEBPS/Text/part0015.xhtml;u171-ch09-030)。
- 结论依据:完整读取本条问题、方案、代码与讨论;结论按真实控制流和适用前提表达,额外边界明确为解释或推导,示例未执行。
- 原始内容:def named_tuple(classname, fieldnames): # Populate a dictionary of field property accessors cls_dict = { name: property(operator.itemge
- 位置:《Python Cookbook(第3版)中文版》9.19 在定义的时候初始化类成员(spine17;extracted/Python Cookbook(第3版)中文版/_epub-src/OEBPS/Text/part0015.xhtml;u172-ch09-030)。
- 结论依据:9.19 StructTupleMeta在类定义期装property,StructTuple new构造tuple,说明两个不同阶段。
- 原始内容:property(operator.itemgetter(n))) class StructTuple(tuple, metaclass=StructTupleMeta): _fields = [] def __new__(cls, *args): if len(arg