方案一:定义一系列数值常量或枚举类型
#1.数值常量
NAME, AGE, SEX, EMAIL = range(4) #元组拆包
student = ('Jim', 16, 'male', 'jim2333@gmail.com')
student[EMAIL]
执行结果:'jim2333@gmail.com'
#2.枚举类型
student = ('Jim', 16, 'male', 'jim2333@gmail.com')
teacher = (34, 'xinghai')
from enum import IntEnum
class StudentEnum(IntEnum):
NAME, AGE, SEX, EMAIL = range(4)
student[StudentEnum.NAME] #NAME, AGE, SEX, EMAIL是int的实例(isinstance(StudentEnum.NAME, int))
执行结果:'Jim'
方案二:使用标准库中collections.namedtuple替代内置tuple
from collections import namedtuple #命名元组
Student = namedtuple('Student', ['name', 'age', 'sex', 'email']) #返回一个元组的子类
student = Student('Jim', 16, 'male', 'jim2333@gmail.com')
student.age #也可以用元组的访问方式student[1]
执行结果:16