• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
孙龙 程序员
少时总觉为人易,华年方知立业难
博客园    首页    新随笔    联系   管理    订阅  订阅
详解Python中的__getitem__方法与slice对象的切片操作
 1 import numbers
 2 from collections import abc
 3 class Group:
 4     #支持切片操作
 5     def __init__(self, group_name, company_name, staffs):
 6         self.group_name = group_name
 7         self.company_name = company_name
 8         self.staffs = staffs
 9 
10     def __reversed__(self):
11         self.staffs.reverse()
12 
13     def __getitem__(self, item):
14         cls = type(self)
15         if isinstance(item, slice):
16             return cls(group_name=self.group_name, company_name=self.company_name, staffs=self.staffs[item])
17         elif isinstance(item, numbers.Integral):
18             return cls(group_name=self.group_name, company_name=self.company_name, staffs=[self.staffs[item]])
19 
20     def __len__(self):
21         return len(self.staffs)
22 
23     def __iter__(self):
24         return iter(self.staffs)
25 
26     def __contains__(self, item):
27         if item in self.staffs:
28             return True
29         else:
30             return False
31 #如果key是一个整形的话就返回列表元素,如果是一个slice对象的话,就创建一个实例并返回。
32 staffs = ["bobby1", "imooc", "bobby2", "bobby3"]
33 group = Group(company_name="imooc", group_name="user", staffs=staffs)
34 reversed(group)
  for循环会调用
__iter__方法,返回了一个迭代器
35 for user in group:
36   print(user)
print(group[:2].staffs)
print(group[2].staffs)
会调用__getitem__方法


class _List(object):
    def __getitem__(self, item):
        print(item)


I = _List()
I[3] //输出:3
I[1:3]//输出:slice(1, 3, None)

  

 

本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/articles/9384887.html

posted on 2018-07-29 12:08  孙龙-程序员  阅读(636)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3