What are “named tuples” in Python?

前端 未结 11 2210
名媛妹妹
名媛妹妹 2020-11-22 06:58

Reading the changes in Python 3.1, I found something... unexpected:

The sys.version_info tuple is now a named tuple:

11条回答
  •  无人共我
    2020-11-22 07:31

    Another way (a new way) to use named tuple is using NamedTuple from typing package: Type hints in namedtuple

    Let's use the example of the top answer in this post to see how to use it.

    (1) Before using the named tuple, the code is like this:

    pt1 = (1.0, 5.0)
    pt2 = (2.5, 1.5)
    
    from math import sqrt
    line_length = sqrt((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2)
    print(line_length)
    

    (2) Now we use the named tuple

    from typing import NamedTuple, Number
    

    inherit the NamedTuple class and define the variable name in the new class. test is the name of the class.

    class test(NamedTuple):
    x: Number
    y: Number
    

    create instances from the class and assign values to them

    pt1 = test(1.0, 5.0)   # x is 1.0, and y is 5.0. The order matters
    pt2 = test(2.5, 1.5)
    

    use the variables from the instances to calculate

    line_length = sqrt((pt1.x-pt2.x)**2 + (pt1.y-pt2.y)**2)
    print(line_length)
    

提交回复
热议问题