Python 2.7 如何自定义一个CLASS风格的字典类型?
发布网友
发布时间:2022-03-03 18:03
我来回答
共2个回答
热心网友
时间:2022-03-03 19:32
import operator
class NewDict( dict ):
default = None
def __init__( self ,init_dict ,default ):
self.default = default
for key ,value in init_dict.items( ):
if isinstance( value ,dict ):
init_dict[ key ] = self.__class__( value ,default )
return super( NewDict ,self ).__init__( init_dict )
def __missing__( self ,key ):
return self.default
def __getattr__( self ,key ):
return operator.getitem( self ,key )
def __setattr__( self ,key ,value ):
if key in dir( self ):
return super( NewDict ,self ).__setattr__( key ,value )
return operator.setitem( self ,key ,value )追问还有2个小问题,补充在提问区域的结尾了,幸苦大神再指点下哈:
热心网友
时间:2022-03-03 20:50
#!/usr/bin/python
# encoding: utf-8
#
# filename: dictObj.py
# author: Tim Wang
# date: Oct., 2013
class DictObj(dict):
def __init__(self, **kwgs):
self.__dict__ = dict(kwgs)
def __getitem__(self, k):
return self.__dict__.get(k, None)
def __setitem__(self, k, value):
self.__dict__[k] = value
def tester():
d = DictObj(name='tim', email='tim_spac@163.com')
print d['name'], d.email
if __name__ == "__main__":
tester()
追问用我定义的那个字典来测试:
print cdic.ten
AttributeError: 'DictObj' object has no attribute 'ten'