UnfinishedPython
Python的collections模块提供了工厂函数nametuple(),在使用tuples类型的数据时,创建更加Pythonic的代码。
Tuple
Tuple是Python的一种数据结构,tuples的主要特点是其不可修改,另一方面,仅可以通过整形index进行索引访问,先看一个简单的例子:
person = ('Milton', 'Banana', 174)
type(person)
# <type 'tuple'>
# Item accessing
print(person[0], person[1], person[2])
# ('Milton', 'Male', 174)
# Immutability
person[0] = 'Miguel'
""" ----------------
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
"""
从可读性的角度上来说,上面获取数据的方法可读性较差,需要记住tuples中每个元素所对应的index才可以实现清楚地获取数据。
namedtuple
nametuple可以有效地解决上述的缺点,在tuple基础上增加了names,这样可以使代码可读性更高。
from collections import namedtuple
Person = namedtuple('Person',['name','gender','height'])
person = Person('Curry', 'Male', 30)
issubclass(person, tuple)
print(person)
print(person.name, person.gender, person.height)
person.name='Green'
NameTuple
from typing import NamedTuple
class Person(NamedTuple):
name: str
age: int
height: int
ears: int = 2
eyes: int = 2
milton = Person(
name="Milton",
age=25,
height=174,
eyes=1)
print(milton.name)