声明:参考B站视频,自学成长记录
https://www.bilibili.com/video/BV1Cq4y1Q7Qv?p=29
默认情况对象不支持切片操作
class Group:
'''默认情况'''
def __init__(self, group_name, staffs):
self.group_name = group_name
self.staffs = staffs
staffs = ['bll1', 'bll2', 'bll3', 'bll4']
group = Group(group_name='小组1', staffs=staffs)
try:
# 切片 - 取区间
group[:2]
except Exception as e:
print(e) # 'Group' object is not subscriptable 不可下标
finally:
# 切片 - 取某个索引得值
group[0] # TypeError: 'Group' object does not support indexing 不支持索引
通过__getitem__魔法函数实现可切片的对象
import numbers
class Group:
'''实现切片操作'''
def __init__(self, group_name, staffs):
self.group_name = group_name
self.staffs = staffs
# 实现切片
def __getitem__(self, item):
# 获取自身得类型
cls = type(self)
# 判断传入item是否为slice类型
if isinstance(item, slice):
return cls(group_name=self.group_name, staffs=self.staffs[item])
# 判断传入item是否为整数类型
elif isinstance(item, numbers.Integral):
return cls(group_name=self.group_name, staffs=[self.staffs[item]])
# 获取长度
def __len__(self):
return len(self.staffs)
# 迭代器
def __iter__(self):
return iter(self.staffs)
# 反转字符串
def __reversed__(self):
self.staffs.reverse()
# 判断字符串是否存在
def __contains__(self, item):
if item in self.staffs:
return True
else:
return False
staffs = ['bll1', 'bll2', 'bll3', 'bll4']
group = Group(group_name='小组1', staffs=staffs)
# 切片
print(group[::2].staffs) # ['bll1', 'bll3']
# 长度
print(len(group)) # 4
# 判断子字符串是否存在
if 'bll1' in group:
print('yes')
else:
print('no')
# 遍历
for g in group:
print(g)
# 反转
reversed(group)
print(group.staffs) # ['bll4', 'bll3', 'bll2', 'bll1']