Python namedtuple named tuple

Named tuples (namedtuple) is a set of one element with attributes, which are a good combination of read-only data.

Compared to the general tuple structure named tuples need to import namedtuple, because it is not the default namespace. Then define a named tuple by name and attributes. This will return a like classes, objects can be instantiated multiple times.

Named tuples can be packed, unpacked and do all of the ordinary tuples can do, and can also be accessed as an object as one of its attributes.

Named tuples is perfect for it indicates that "data only", but not very ideal for all situations. And like strings and tuples, tuples are immutable name, and thus once set values ​​for the attributes can not be changed.

If you need to modify the data stored in a dictionary type would be more appropriate.

from collections import namedtuple

# 创建一个namedtuple的学生类,第一个参数是命名元组的名称,第二个参数是命名元组的属性,多个用空格隔开(或者逗号)
Student = namedtuple('Student', 'gender age height')

# 实例化学生,赋予属性,和上面第二个参数相对应
Miles = Student('Male', 24, 1.92)
Mary = Student('Female', 18, 1.68)

# 查看属性
print(Miles)            # 查看Miles所有属性
print(Mary.height)      # 查看Mary的身高
print(Miles[1])         # 通过索引查看Miles的年龄
print('==============')

# 遍历元组
for i in Mary:
    print(i)

Output:

Student(gender='Male', age=24, height=1.92)
1.68
24
==============
Female
18
1.68

Guess you like

Origin www.cnblogs.com/milesma/p/12155841.html