NAME = 0
AGE = 1
SEX = 2
EMAIL = 3
student = ('Dimples', 23, '女', '[email protected]')
if student[AGE] >= 18: # student[1] >= 18
pass
if student[SEX] == '女': # student[2] == '女'
pass
使用标准库中 collections.namedtuple 替代内置tuple
from collections import namedtuple
相当于类的工厂:
Student = namedtuple('Student', ['name', 'age', 'sex', 'email'])
s = Student('Dinples', 23, '女', '[email protected]')
以类对象的形式访问元组:
s.name
# s是内置类型tuple的一个子类