美文网首页
30.5-魔术方法—容器化魔术方法

30.5-魔术方法—容器化魔术方法

作者: BeautifulSoulpy | 来源:发表于2019-12-25 09:00 被阅读0次

只有一次的人生,拿出干劲来啊你!


容器化魔术方法:能将 实例对象伪装成 一个容器list\set\等

总结:

  1. 这几个容器化方法非常非常重要;特别是 getitem、setitem;
  2. 字典和列表的内存实现是完全不同的;

1. 容器化魔术方法

class A(dict):
    def __missing__(self,key):   # missing方法的用处;
        print('Miss key {}'.format(key))
        return 123
    
a = A()
print(a['k'])      # 
print(a.get('k'))  # get 找不到会找默认值 None;
#-----------------------------------------------------------------------------------------------------
Miss key k
123
None

练习:
将购物车类改造成方便操作的容器类;

_len_ _iter_ 方法的使用范例;

class Cart:
    def __init__(self):
        self.items = []

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

    def additem(self, item):
        self.items.append(item)

    def __iter__(self):
        # yield from self.items  # 等价形式;
        return iter(self.items)  # 返回一个迭代器;

    def __getitem__(self, index): # 索引访问值value;
        return self.items[index]
    
cart = Cart()
cart.additem(1)
cart.additem('abc')
cart.additem(3)
cart.additem(4)

print(len(cart))  # 4
for x in cart:  # 迭代购物车对象 ;
    print(x)
#-------------------------------------------------------------------------------
4
1
abc
3
4
class Cart:
    def __init__(self):
        self.__items = []
        
    def __len__(self):
        return len(self.__items)
    
    def additem(self, item):
        self.__items.append(item)
        
    def __iter__(self):
        yield from self.__items
        #return iter(self.items)  # 返回一个迭代器;
    
    def __getitem__(self, index): # 索引访问
        return self.__items[index]
    
    def __setitem__(self,index,value):
        self.__items[index] = value
        
    def __add__(self,other):
        self.__items.append(other)
        return self
    
cart = Cart()
cart.additem(1)
cart.additem('abc')
cart.additem(3)
cart.additem(4)

print(len(cart))  # 4
print(cart[1])
cart[1]=2
for x in cart:  # 迭代购物车对象 ;
    print(x)
    
print(2 in cart)

cart + 11 + 12  # __add__ 方法;  链式编程;
cart.__add__(13).__add__(14)
print(list(cart))   # 
#--------------------------------------------------------------------------------
4
abc
1
2
3
4
True
[1, 2, 3, 4, 11, 12, 13, 14]

相关文章

网友评论

      本文标题:30.5-魔术方法—容器化魔术方法

      本文链接:https://www.haomeiwen.com/subject/dybcoctx.html