Python 的 用 __getitem__ 实现序列协议

等级 4164 次按键

实现 __len__ 和 __getitem__,让类可以配合 len()、索引和 list() 使用。

Python 代码

1class Deck:
2 cards = ["A", "K", "Q"]
# len(d) 会调用 __len__ 并返回 3
3 def __len__(self):
4 return len(self.cards)
# d[i] 会调用 __getitem__;list() 也使用它,依次请求索引 0、1、2,直到出现 IndexError
5 def __getitem__(self, i):
6 return self.cards[i]
7d = Deck()
# 打印 3 A ['A', 'K', 'Q']
8print(len(d), d[0], list(d))

运行结果

3 A ['A', 'K', 'Q']
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 Python 代码中需要输入的符号及其出现次数。

  • _× 8
  • (× 7
  • )× 7
  • "× 6
  • ,× 5
  • :× 3
  • [× 3
  • ]× 3
  • .× 2
  • =× 2

Python 等级 4 的更多代码示例

← 返回 Python 打字练习