• 对UserDict的研究


    # -*- coding: utf-8 -*-
    #python 27
    #xiaodeng
    #对UserDict的研究
    
    
    class UserDict():
        def __init__(self, dict=None, **kwargs):
            self.data = {}  #定义self.data
            if dict is not None:
                self.update(dict)
            if len(kwargs):
                self.update(kwargs)
            #print self.data  #构造函数
                
        def __repr__(self):#有该语句,a=UserDict(b),print a时,可打印实例内容
            return repr(self.data) 
        
        def __cmp__(self, dict):
            if isinstance(dict, UserDict):
                return cmp(self.data, dict.data)
            else:
                return cmp(self.data, dict)
        __hash__ = None # Avoid Py3k warning
        
        def __len__(self):
            '''
            给类构造长度运算方式,当a=UserDict(b)实例化时,print len(a)才能有运算结果
            没有__len__语句,会报错,
            如:AttributeError: UserDict instance has no attribute '__len__'
            提示说明:UserDict instance(UserDict实例)没有__len__属性
            '''
            return len(self.data)
        
        
        def __getitem__(self, key):
            if key in self.data:
                return self.data[key]
            if hasattr(self.__class__, "__missing__"):
                return self.__class__.__missing__(self, key)
            raise KeyError(key)
    
        
        def __setitem__(self, key, item):
            '''
            #__setitem__,不需要返回值,所以没有return
            #怎么调用?
            #a['a']=5
            '''
            self.data[key] = item
            
        #__delitem__,不需要返回值,所以没有return
        def __delitem__(self, key):
            '调用方式:del a[key]'
            del self.data[key]
        
        def clear(self): self.data.clear()
        
        def copy(self):
            if self.__class__ is UserDict:
                return UserDict(self.data.copy())
            import copy
            data = self.data
            try:
                self.data = {}
                c = copy.copy(self)
            finally:
                self.data = data
            c.update(self)
            return c
        
        def keys(self):
            '''
            >>> a.keys() #key键
            ['age', 'name', 'laiYuan']
            '''
            return self.data.keys()#注意data不能省略
        
        def items(self):
            return self.data.items()
        
        def iteritems(self):
            return self.data.iteritems()
        
        def iterkeys(self):
            return self.data.iterkeys()
        
        def itervalues(self):
            return self.data.itervalues()
        
        def values(self):
            '''
            >>> a.values()
            [28, 'xiaodeng', 'hubei']
            '''
            return self.data.values()
        def has_key(self, key): return key in self.data
    
        #更新操作
        def update(self, dict=None, **kwargs):
            if dict is None:
                pass
            elif isinstance(dict, UserDict):
                self.data.update(dict.data)
            elif isinstance(dict, type({})) or not hasattr(dict, 'items'):
                self.data.update(dict)
            else:
                for k, v in dict.items():
                    self[k] = v
            if len(kwargs):
                self.data.update(kwargs)
                
        def get(self, key, failobj=None):
            '''
            failobj:预定义内容,
            该段小代码的意思是key是否在self中,如果不存在,则返回failobj,如存在可返回其value值
            print a.get('name')#failobj用预定义的值None
            print a.get('YuYan','python')
            '''
            if key not in self:
                return failobj
            return self[key]
        
        def setdefault(self, key, failobj=None):
            '与get有异曲同工之妙'
            if key not in self:
                self[key] = failobj
            return self[key]
        
        def pop(self, key, *args):
            return self.data.pop(key, *args)
        
        
        def popitem(self):
            '删除并返回dict中任意的一个(key,value)队,如果字典为空会抛出KeyError'
            'KeyError:popitem(): dictionary is empty'
            return self.data.popitem()
        
        def __contains__(self, key):
            return key in self.data
        @classmethod
        def fromkeys(cls, iterable, value=None):
            d = cls()
            for key in iterable:
                d[key] = value
            return d
    if __name__=='__main__':
        b={'name':'xiaodeng','age':28,'laiYuan':'hubei'}
        a=UserDict(b)
        print a
        print len(a)
        print a.get('name')
        print a.get('bb','python')
  • 相关阅读:
    代理模式(Proxy)
    桥接模式(Bridge)
    组合模式(Composite)
    装饰器模式(Decorator)
    外观模式(Facade)
    享元模式(FlyWeight)
    职责链模式(Chain of Responsibility)
    迭代器模式(Iterator)
    中介者模式(Mediator)
    命令模式(Command)
  • 原文地址:https://www.cnblogs.com/dengyg200891/p/4889172.html
Copyright © 2020-2023  润新知