python整理二十二——dict类型用点号访问

看了一部分webpy的源码,里面有些代码挺有用,扣出来用用,其中dict类型用属性到方式访问:

d1 = {'csdn' : 'csdn.net'}

取值 d1['csdn'] ---> 'csdn.net'

用点号访问 d1.csdn ---> 'csdn.net'

 

------------------------------------------------------------

class Storage(dict): """ A Storage object is like a dictionary except `obj.foo` can be used in addition to `obj['foo']`. >>> o = storage(a=1) >>> o.a 1 >>> o['a'] 1 >>> o.a = 2 >>> o['a'] 2 >>> del o.a >>> o.a Traceback (most recent call last): ... AttributeError: 'a' """ def __getattr__(self, key): try: return self[key] except KeyError, k: raise AttributeError, k def __setattr__(self, key, value): self[key] = value def __delattr__(self, key): try: del self[key] except KeyError, k: raise AttributeError, k def __repr__(self): return ''

你可能感兴趣的:(Python,web)