訪問元組的信息時,我們使用索引(index)訪問,會大量降低程序可讀性,所以用以下兩種方式可以解決這個問題。
定義類似於其他語言的枚舉類型,也就是定義一系列數值常量
使用標準庫中 collections.namedtuple 替代內置tuple
方法一:
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
相當於類的工廠:
類型 = namedtuple('創建子類的名字’,[一系列的名字])
Student = namedtuple('Student', ['name', 'age', 'sex', 'email'])s = Student('Dinples', 23, '女', '[email protected]')
以類對象的形式訪問元組:
s.name