mis*_*ope 3 python dto namedtuple python-2.7 python-attrs
前言
\n\n我想知道如何以Python方式概念化数据类。\n特别是我\xe2\x80\x99m 谈论 DTO(数据传输对象)。
\n\n我在 @jeff-oneill 问题 \xe2\x80\x9c使用 Python 类作为数据容器\xe2\x80\x9d 中找到了一个很好的答案,其中 @joe-kington 很好地使用了内置namedtuple.
问题
\n\n在 python 2.7 文档的第 8.3.4 节中,有一个关于如何组合多个命名元组的很好的示例。\n我的问题是如何实现相反的效果?
\n\n例子
\n\n考虑文档中的示例:
\n\n>>> p._fields # view the field names\n(\'x\', \'y\')\n\n>>> Color = namedtuple(\'Color\', \'red green blue\')\n>>> Pixel = namedtuple(\'Pixel\', Point._fields + Color._fields)\n>>> Pixel(11, 22, 128, 255, 0)\nPixel(x=11, y=22, red=128, green=255, blue=0)\nRun Code Online (Sandbox Code Playgroud)\n\n如何从 \xe2\x80\x9cPixel\xe2\x80\x9d 实例推断出 \xe2\x80\x9cColor\xe2\x80\x9d 或 \xe2\x80\x9cPoint\xe2\x80\x9d 实例?
\n\n最好是具有蟒蛇精神。
\n这里是。顺便说一下,如果你经常需要这个操作,你可以创建一个函数来进行color_ins创建,基于pixel_ins. 或者甚至对于任何子命名元组!
from collections import namedtuple
Point = namedtuple('Point', 'x y')
Color = namedtuple('Color', 'red green blue')
Pixel = namedtuple('Pixel', Point._fields + Color._fields)
pixel_ins = Pixel(x=11, y=22, red=128, green=255, blue=0)
color_ins = Color._make(getattr(pixel_ins, field) for field in Color._fields)
print color_ins
Run Code Online (Sandbox Code Playgroud)
输出:Color(red=128, green=255, blue=0)
用于提取任意子命名元组的函数(无错误处理):
def extract_sub_namedtuple(parent_ins, child_cls):
return child_cls._make(getattr(parent_ins, field) for field in child_cls._fields)
color_ins = extract_sub_namedtuple(pixel_ins, Color)
point_ins = extract_sub_namedtuple(pixel_ins, Point)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1159 次 |
| 最近记录: |