_field_defaults Attribute Of A Namedtuple

Attribute Name:

_field_defaults

Overview:

  • _field_defaults attribute has the default values for the fields of a named tuple.
  • Using the defaults parameter of the namedtuple constructor function, default values can be specified for one or mode fields.

 

Example:

# Example Python program that uses the defaults parameter while creating namedtuple instances

import collections

 

# Create a named tuple called speed

speed   = collections.namedtuple("speed", "vehicle_number , speed, timestamp, tyrecount", defaults=[4]);

 

# Create speed records for vehicles

s1      = speed("xxxxxxx-xxxxxx", 65, "12:01:12");

s2      = speed("xxxxxxx-xxxxxx", 70, "12:01:12", 6);

 

# Print default values for name tuple

print(s2._field_defaults);

 

# Print speed records

print(s1);

print(s2);

 

Output:

{'tyrecount': 4}

speed(vehicle_number='xxxxxxx-xxxxxx', speed=65, timestamp='12:01:12', tyrecount=4)

speed(vehicle_number='xxxxxxx-xxxxxx', speed=70, timestamp='12:01:12', tyrecount=6)


Copyright 2022 © pythontic.com