如何为元组中的每个元素命名,提高程序的可读性?

需求:
学生信息系统中信息为固定格式,(姓名,年龄,性别,邮箱)
('jim',16,male,jim@goole.com)
访问时,我们使用索引(index)访问,大量索引降低了程序的可读性

思路:
1、定义一系列,数值常量和枚举类型
2、使用标准库collections.namedtuple替代内置的tuple

代码

方法一:
# 使用数值常量
NAME,AGE,SEX,EMAIL = range(4) # 使用元组有拆包,0,1,2,3分别赋值给它们

def xxx_func(student):      
    if student[AGE] < 18:
        pass
    if student[SEX] == 'male':
        pass

    # ...

student = ('Jim',16,'male','Jime@gmail.com')
xxx_func(student)

# 使用杖举类型
In [1]: student = ('Jim',16,'male','Jime@gmail.com')

In [2]: t = (34,'kangkang')

In [3]: from enum import IntEnum

In [4]: class StudentEnum(IntEnum):
   ...:     NAME = 0
   ...:     AGE = 1
   ...:     SEX = 2
   ...:     EMAIL = 3
   ...: 

In [5]: StudentEnum.NAME
Out[5]: <StudentEnum.NAME: 0>

In [6]: s[StudentEnum.NAME]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-ef32198656ca> in <module>
----> 1 s[StudentEnum.NAME]

NameError: name 's' is not defined

In [7]: student[StudentEnum.NAME]
Out[7]: 'Jim'

In [8]: isinstance(StudentEnum.NAME,int)
Out[8]: True

In [9]: StudentEnum.NAME == 0
Out[9]: True

方法二:使用命名元组,通过属性来访问元组中的元素
In [10]: from collections import namedtuple

In [11]: Student  = namedtuple('Studnet',['name','age','sex','email'])

In [12]: s2 = Student('Jim',16,'male','jim@gmial.com')

In [13]: s2
Out[13]: Studnet(name='Jim', age=16, sex='male', email='jim@gmial.com')

In [14]: isinstance(s2.tuple)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-14-2c0a9e73bea0> in <module>
----> 1 isinstance(s2.tuple)

AttributeError: 'Studnet' object has no attribute 'tuple'

In [15]: isinstance(s2,tuple)
Out[15]: True

In [16]: s2[0]
Out[16]: 'Jim'

In [17]: s2[1]
Out[17]: 16

In [18]: s2['name']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-18-de79b81449a0> in <module>
----> 1 s2['name']

TypeError: tuple indices must be integers or slices, not str

In [19]: s2.name
Out[19]: 'Jim'

In [20]: s2.age
Out[20]: 16

In [21]: 
posted @ 2020-10-29 16:58  Richardo-M-Lu  阅读(72)  评论(0编辑  收藏  举报