What is Python mapping to Ada / C ++ structure type?

Suppose I am recording data and want to link a number of data elements, so that each recorded set always has a fixed composition, that is, missing fields.

Most of my programming experience is with Ada or C / C ++ variants. In Ada, I would use the record type and aggregate assignment, so when the record type has been updated with new fields, anyone who uses this record will be notified by the compiler. In C ++, most likely I would use a storage class and constructor to do something like this.

What is the appropriate way to handle this situation in Python? Is this the case when classes are the correct answer, or is there a lighter weight analogue of Ada's notation?

An additional thought, both Ada records and C ++ constructors allow default initialization values. Is there a Python solution for the above question that also provides this feature?

+3
source share
2 answers

A namedtuple (from the collection library) can meet your goals. This is basically a tuple that allows you to refer to fields by name, as well as the index position. Thus, this is a fixed structure of ordered named fields. It is also facilitated by what it uses slotsto determine field names, thereby eliminating the need to transfer the dictionary in each instance.

A typical use case is the definition of a point:

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

, , , . replace, , .

namedtuple, Recipes 576555 ActiveState Python, records, . , .

+4

- Python. , , .

config = {'maxusers': 20, 'port': 2345, 'quota': 20480000}

collections.namedtuple() - Python, .

+3

All Articles