Ada 记录/C++ 结构类型的 Python 对应物是什么? [英] What is the Python counterpart to an Ada record / C++ struct type?

查看:30
本文介绍了Ada 记录/C++ 结构类型的 Python 对应物是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在记录数据并且想要关联一些数据元素,这样每个记录集总是有一个固定的组成,即没有丢失的字段.

Suppose I am recording data and want to associate some number of data elements, such that each recorded set always has a fixed composition, i.e. no missing fields.

我作为程序员的大部分经验都与 Ada 或 C/C++ 变体有关.在 Ada 中,我将使用记录类型和聚合赋值,这样当记录类型更新为新字段时,编译器会通知任何使用该记录的人.在 C++ 中,我可能会使用存储类和构造函数来做类似的事情.

Most of my experience as a programmer is with Ada or C/C++ variants. In Ada, I would use a record type and aggregate assignment, so that when the record type was updated with new fields, anyone using the record would be notified by the compiler. In C++, chances are I would use a storage class and constructor to do something similar.

在 Python 中处理类似情况的合适方法是什么?这是类是正确答案的情况,还是与 Ada 记录类似的重量更轻?

What is the appropriate way to handle a similar situation in Python? Is this a case where classes are the proper answer, or is there a lighter weight analog to the Ada record?

另外一个想法,Ada 记录和 C++ 构造函数都允许默认初始化值.是否有针对上述问题的 Python 解决方案也提供了该功能?

An additional thought, both Ada records and C++ constructors allow for default initialization values. Is there a Python solution to the above question which provides that capability as well?

推荐答案

A namedtuple(来自集合库)可能适合您的目的.它基本上是一个元组,允许按名称和索引位置引用字段.所以它是有序命名字段的固定结构.它也是轻量级的,因为它使用 slots 来定义字段名称,从而消除了在每个实例中都携带字典的需要.

A namedtuple (from the collections library) may suit your purposes. It is basically a tuple which allows reference to fields by name as well as index position. So it's a fixed structure of ordered named fields. It's also lightweight in that it uses slots to define field names thus eliminating the need to carry a dictionary in every instance.

一个典型的用例是定义一个点:

A typical use case is to define a point:

from collections import namedtuple
Point = namedtuple("Point", "x y")
p1 = Point(x=11, y=22)

它的主要缺点是,作为一个元组,它是不可变的.但是有一种方法 replace 允许您用新值替换一个或多个字段,但在此过程中会创建一个新实例.

It's main drawback is that, being a tuple, it is immutable. But there is a method, replace which allows you to replace one or more fields with new values, but a new instance is created in the process.

ActiveState Python Recipes 576555 中还有一个名为 records 的可变版本的命名元组允许直接字段更改.我已经使用过它并且可以保证它运行良好.

There is also a mutable version of namedtuple available at ActiveState Python Recipes 576555 called records which permits direct field changes. I've used it and can vouch that it works well.

这篇关于Ada 记录/C++ 结构类型的 Python 对应物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆