Python序列协议
一、序列协议
只要实现了__getitem__和__len__方法,就会被认为是序列。
示例:
class Sequence:
def __init__(self, string):
self.str = string
def __getitem__(self, item):
return item
def __len__(self):
return len(self.str)
二、切片原理
示例:
class Sequence:
def __init__(self, string):
self.str = string
def __getitem__(self, item):
return item
def __len__(self):
return len(self.str)
ss = Sequence("abcdef")
print(ss[1])
print(ss[1:4])
print(ss[1:4:2])
print(ss[1:4:2, 7:9])
components = [1, 2, 3, 4, 5, 6]
step = slice(0, 5, 2)
print(components[step])
运行结果
网友评论