Pthon魔术方法(Magic Methods)-容器相关方法

           Pthon魔术方法(Magic Methods)-容器相关方法

                                      作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

一.容器相关方法汇总

  __len__:
    内建函数len(),返回对象的长度(>=0的整数),如果把对象当作容器类型看,就如同list或者dict。
    bool()函数调用的时候,如果没有__bool__()方法,则会看__len__()方法是否存在,存在返回非0为真。

  __iter__:
    迭代容器时,调用,返回一个新的迭代器对象。

  __contains__:
    in成员运算符,没有实现,就调用__iter__方法遍历

  __getitem__:
    实现self[key]访问。序列对象,key接受整数位索引,或者切片。对于set和dict,key为hashable。key不存在引发KeyError异常。

  __settitem__:
    和__getitem__的访问类似,是设置值的方法。

  __missing__:
    字典或者子类使用__getitem__()调用时,key不存在执行该方法。

二.案例展示

1>.__missing__案例展示

 1 #!/usr/bin/env python
 2 #_*_conding:utf-8_*_
 3 #@author :yinzhengjie
 4 #blog:http://www.cnblogs.com/yinzhengjie
 5 
 6 class A(dict):
 7     def __missing__(self, key):
 8         print("Missing key : {}".format(key))
 9         return 0
10 
11 a = A()
12 print(a["name"])
13 
14 
15 
16 #以上代码执行结果如下:
17 Missing key : name
18 0

2>.将购物车类改造成方便操作的容器类案例

 1 #!/usr/bin/env python
 2 #_*_conding:utf-8_*_
 3 #@author :yinzhengjie
 4 #blog:http://www.cnblogs.com/yinzhengjie
 5 
 6 class Cart:
 7     def __init__(self):
 8         self.items = []
 9 
10     def __len__(self):
11         return len(self.items)
12 
13     def additem(self,item):
14         self.items.append(item)
15 
16     def __iter__(self):
17         yield from self.items
18 
19     def __getitem__(self, index):       #索引访问
20         return self.items[index]
21 
22     def __setitem__(self, key, value):  #索引赋值
23         self.items[key] = value
24 
25     def __str__(self):
26         return str(self.items)
27 
28     def __add__(self, other):           #算数运算符+
29         self.items.append(other)
30         return self
31 
32 cart = Cart()
33 cart.additem("Iphone 11")
34 cart.additem("康佳单反")
35 cart.additem("篮球")
36 
37 #长度,bool
38 print(len(cart))
39 print(bool(cart))
40 
41 #迭代
42 for item in cart:
43     print(item)
44 
45 #in
46 print("篮球" in cart)
47 print("Iphone 11" in cart)
48 
49 #索引操作
50 print(cart[1])
51 cart[1] = "Jason Yin"
52 
53 
54 #链式编程实现加法
55 print(cart + 100 + 200 + 300)
56 print(cart.__add__(2019).__add__(2120))
57 
58 
59 
60 #以上代码执行结果如下:
61 3
62 True
63 Iphone 11
64 康佳单反
65 篮球
66 True
67 True
68 康佳单反
69 ['Iphone 11', 'Jason Yin', '篮球', 100, 200, 300]
70 ['Iphone 11', 'Jason Yin', '篮球', 100, 200, 300, 2019, 2120]
原文地址:https://www.cnblogs.com/yinzhengjie/p/11241321.html