point = (3, 5)
# 输出x,y坐标
print(point[0], point[1])
3 5
namedtuple
允许创建有属性名称的元组,这样就可以通过属性名称来获取数据。
from collections import namedtuple
Point = namedtuple('Point', ['x_coord', 'y_coord'])
print(issubclass(Point, tuple))
True
point = Point(3, 5)
# 输出x,y坐标
print(point.x_coord, point.y_coord)
3 5
程序输出结果:
True
3 5
class Point():
def __init__(self, x, y):
self.x_coord = x
self.y_coord = y
point = Point(3, 5)
# 输出x,y坐标
print(point.x_coord, point.y_coord)
3 5
为什么不使用类,而使用 namedtuple
,最常见的解释是定义一个类大材小用,
这种想法是不对的,原因有两点:
- 创建一个
namedtuple
对象,不比创建一个类简单。 namedtuple
返回的对象本身就是一个类,这和直接创建类没有区别。
真正的原因是元组,元组是不可变对象,因此元组可以做字典的 key
,可以存储到集合中,
如果用自定义的普通类来替代 namedtuple
,一旦需要做字典的 key
,
那么普通的类创建出的对象就无能为力了。而 namedtuple
创建的是 tuple
的子类,
因此具有 tuple
的一切属性。