实现具名元组类
在这一步中,你将学习如何实现 具名元组 类,它允许你使用位置索引和属性名来访问数据。
- 在你的代码编辑器中打开
namedtuple.py 文件。
- 定义
具名元组 类,它应该继承自 tuple 类。
- 在
__init__ 方法中,接受两个参数:iterable(数据)和 fields(数据的名称)。
- 将
iterable 和 fields 分别存储为实例变量 self.data 和 self.fields。
- 使用
for 循环遍历 fields,并将每个字段设置为 具名元组 实例的一个属性,从 self.data 中分配相应的值。
- 实现
__new__ 方法来创建 具名元组 类的一个新实例。此方法应调用 tuple 类的 __new__ 方法并返回新实例。
- 实现
__getitem__ 方法,以允许使用位置索引和属性名来访问数据。如果索引是一个字符串,则在 self.fields 中找到相应字段的索引,并从 self.data 中返回值。
- 实现
__repr__ 方法,以 具名元组(x=1, y=2) 的格式返回 具名元组 实例的字符串表示形式,其中 x 和 y 是字段名,1 和 2 是相应的值。
你完成的 具名元组 类应该如下所示:
class NamedTuple(tuple):
def __init__(self, iterable, fields):
self.data = iterable
self.fields = tuple(fields)
for i, attr in enumerate(self.fields):
setattr(self, attr, self.data[i])
def __new__(cls, iterable, fields):
return super().__new__(cls, iterable)
def __getitem__(self, index):
if isinstance(index, str):
index = self.fields.index(index)
return self.data[index]
def __repr__(self):
return f"NamedTuple({', '.join(f'{field}={self[field]}' for field in self.fields)})"