您的位置:首页 > 其它

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

2017-07-12 00:58 429 查看
为元组中的每个元素命名,提高程序可读性

元组中,使用索引(index)访问时,会出现大量索引,降低程序的可读性。

解决方法:
1: 定义类似与其他语言的枚举类型,也就是定义一系列数值常量

eg_v1:定义一个学生信息的元组,包括姓名,年龄,性别,邮箱
("aaaa",22,"boy","aaaaa@123.com")
("bbbb",20,"boy","bbbbb@123.com")
("cccc",22,"girl","ccccc@123.com")
("dddd",21,"girl","ddddd@123.com")

Name = 0
Age = 1
Sex = 2
Email = 3

或者: Name,Age,Sex,Email = xrange(4)

student = ("aaaa",22,"boy","aaaaa@123.com")
# name
print (student[Name])
# aaaa

# age
print (student[Age])
# 22

# sex
print (student[Sex])
# boy

# email
print (student[Email])
# aaaaa@123.com


  

2: 使用标准库中的collection.namedtuple函数替换内置tuple函数

from collections import namedtuple  # 导入namedtuple包
Student = namedtuple("Student",["name","age","sex","email"])

s = Student("aaaa",22,"boy","aaaaa@123.com")   # 位置传参
print (s)
# Student(name='eeee', age=25, sex='boy', email='eeeee@123.com')

s2 = Student(name="eeee",age=25,sex="boy",email="eeeee@123.com")   # # 关键字传参
print (s2)
# Student(name='eeee', age=25, sex='boy', email='eeeee@123.com')

print (s.name)
# aaaa

print (s.age)
# 22

print (s.sex)
# boy

print (s.email)
# aaaaa@123.com

print (isinstance(s,tuple))  # 判断是否为tuple元组的子类
# True


  

  

namedtuple 函数的帮助手册:

>>> help(namedtuple)
Help on function namedtuple in module collections:
namedtuple(typename, field_names, verbose=False, rename=False)
Returns a new subclass of tuple with named fields.

>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
>>>


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐