python Defines a named tuple instance operation

  • 2021-09-11 20:53:27
  • OfStack

1. Defining a named tuple requires two parameters. The first parameter is the class name and the second parameter is the field name. It can be an iterable object (such as list and tuple) or a space-spaced string:


Card = collections.namedtuple("Card", ("rank", "suit"))
Card = collections.namedtuple("Card", "rank suit")

2. When initialized, pass in the constructor as a string of parameters:


card_test = Card("J", "hearts")

3. You can use the. operator or the index to get the value:


print(card_test.rank)
print(card_test[1])

Extension of knowledge points:

Definition of named tuples

The named tuple (namedtuple) factory function is defined in the Python standard library collections, which can build tuples with field names.

Detailed solution of factory function parameters

Variable name = namedtuple (typename, field_names, *, rename=False, defaults=None, module=None)

Detailed explanation of parameters of namedtuple factory function:

typename: Defines the name of a named tuple, string type.

field_names: Defines the field name of the named tuple. This parameter can be in two formats:

Internal elements are all lists or tuples of strings;

E.g. ['Commodity', 'Unit Price', 'Quantity'] or ('Commodity', 'Unit Price', 'Quantity')

A long string separated by English commas', '. Field names must comply with the following rules:

E.g. 'merchandise, unit price, quantity '

Field name naming convention:

Cannot have the same name as keyword You cannot start with an underscore It begins with letters (including Chinese characters) and consists of letters, numbers and underscores.

rename: The default is False, meaning that a field name must be specified. For True, the default, duplicate field name is automatically renamed to '_ index value'.

defaults: Set the default value, which can be list or tuple. When the number of fields is greater than the number of elements in defaults, the following fields get the default value.

For example, when the field names are 'a', 'b' and 'c', and the default values are given to '1' and '2', 'b' = 1 and 'c' = 2.

module: Set the module to which it belongs, and the default is' __main__ '.


Related articles: