0%

Python之Sequence Protocol 序列协议

这里介绍Python的Sequence Protocol 序列协议

abstract.png

实践

对于我们自定义的对象,如果期望其可以支持序列的相关操作,只需对该类实现Sequence Protocol序列协议即可。这里我们提供了一个自定义类——一副扑克牌(不包含大小王)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class PlayingCard:
"""
一副扑克牌
"""
# 扑克牌花色
suits = ["黑桃","红桃","梅花","方块"]
# 扑克牌点数
nums = ["A"] + [str(n) for n in range(2,11)] + ["J", "Q", "K"]

def __init__(self):
self.cards = [suit+num for suit in PlayingCard.suits for num in PlayingCard.nums]

def __len__(self):
return len(self.cards)

def __getitem__(self, index):
return self.cards[index]

def __setitem__(self, index, value):
self.cards[index] = value

def __delitem__(self, index):
self.cards[index] = None

len方法

调用len()方法获取长度,Python会自动调用自定义对象的__len__()方法

1
2
3
4
print("-------------------len 方法 -----------------------")
playingCard = PlayingCard()
cards_num = len( playingCard )
print("一副扑克牌中的扑克牌总数:", cards_num)

figure 1.png

索引访问

使用索引访问元素时,Python会自动调用自定义对象的__getitem__()方法

1
2
3
4
5
print("------------------- 索引访问 -----------------------")
playingCard = PlayingCard()
print("playingCard[0]: ", playingCard[0])
print("playingCard[14]: ", playingCard[14])
print("playingCard[-1]: ", playingCard[-1])

figure 2.png

切片

切片时,Python会自动调用自定义对象的__getitem__()方法

1
2
3
4
5
print("------------------- 切片 -----------------------")
playingCard = PlayingCard()

print("playingCard[:4]: ", playingCard[:4])
print("playingCard[-4:-1]: ", playingCard[-4:-1])

figure 3.png

迭代

for循环时我们虽然没有实现__iter__()方法,但是实现了__getitem__()方法。故Python会自动创建一个迭代器,尝试按从索引0开始按顺序获取元素

1
2
3
4
5
6
7
8
9
print("------------------- 循环迭代 -----------------------")
playingCard = PlayingCard()

count=1
for card in playingCard:
print(f"第{count}张扑克牌: {card}")
count = count+1
if( count==4 ):
break

figure 4.png

索引修改

通过索引修改元素时,Python会自动调用自定义对象的__setitem__()方法

1
2
3
4
5
6
print("------------------- 索引修改 -----------------------")
playingCard = PlayingCard()

print("Before Modify: playingCard[:4]: ", playingCard[:4])
playingCard[0], playingCard[1], playingCard[2] = playingCard[1], playingCard[2], playingCard[0]
print("After Modify: playingCard[:4]: ", playingCard[:4])

figure 5.png

del删除

使用del关键字删除元素时,Python会自动调用自定义对象的__delitem__()方法

1
2
3
4
5
6
7
print("------------------- del删除 -----------------------")
playingCard = PlayingCard()

print("Before Delete: playingCard[10:15]: ", playingCard[10:15])
del playingCard[11]
del playingCard[13]
print("After Delete: playingCard[10:15]: ", playingCard[10:15])

figure 6.png

参考文献

  1. Python编程·第3版:从入门到实践 Eric Matthes著
  2. Python基础教程·第3版 Magnus Lie Hetland著
  3. 流畅的Python·第1版 Luciano Ramalho著
请我喝杯咖啡捏~

欢迎关注我的微信公众号:青灯抽丝