python內(nèi)部數(shù)據(jù)容器有dict和list兩種 ,工作中最常用的方式是定義一些數(shù)據(jù)結(jié)構(gòu)(數(shù)據(jù)即代碼),例如:
1 frog={'name':'scott',
2 'age':2,
3 'parts':{
4 'eye':'green','leg':85
5 },
6 ''friend":['moee','wee'],
7 "hometown":'affica'
8 }
2 'age':2,
3 'parts':{
4 'eye':'green','leg':85
5 },
6 ''friend":['moee','wee'],
7 "hometown":'affica'
8 }
frog對(duì)象定義了小動(dòng)物的某些屬性,訪問frog對(duì)象屬性時(shí),通過 dict,list的取值方法進(jìn)行訪問,例如:
print frog['name']
print frog['friend'][0]
有時(shí)覺得這種表達(dá)方式太原始了,需要改進(jìn),最好是以 '.'方式訪問對(duì)象屬性,例如:
print frog.name
代碼來開始和結(jié)束吧, class _x
1 class _x:
2 """
3 從簡(jiǎn)單數(shù)據(jù)類型轉(zhuǎn)換成python對(duì)象
4
5 p = _x({'name':'boob','body':{'color':'black'},'toys':[1,2,3,],'age':100})
6 print p['toys'][1]
7 print len(p.toys)
8 print p.body.colors
9 """
10 def __init__(self,primitive):
11 self.data = primitive
12
13 def __getattr__(self, item):
14 value = self.data.get(item,None)
15 if type(value) == dict:
16 value = _x(value)
17 return value
18
19 def __len__(self):
20 return len(self.data)
21
22 def __str__(self):
23 return str(self.data)
24
25 def __getitem__(self, item):
26 value = None
27 if type(self.data) in (list,tuple):
28 value = self.data[item]
29 if type(value) in (dict,list,tuple):
30 value = _x(value)
31 elif type(self.data) == dict:
32 value = self.__getattr__(item)
33 return value
2 """
3 從簡(jiǎn)單數(shù)據(jù)類型轉(zhuǎn)換成python對(duì)象
4
5 p = _x({'name':'boob','body':{'color':'black'},'toys':[1,2,3,],'age':100})
6 print p['toys'][1]
7 print len(p.toys)
8 print p.body.colors
9 """
10 def __init__(self,primitive):
11 self.data = primitive
12
13 def __getattr__(self, item):
14 value = self.data.get(item,None)
15 if type(value) == dict:
16 value = _x(value)
17 return value
18
19 def __len__(self):
20 return len(self.data)
21
22 def __str__(self):
23 return str(self.data)
24
25 def __getitem__(self, item):
26 value = None
27 if type(self.data) in (list,tuple):
28 value = self.data[item]
29 if type(value) in (dict,list,tuple):
30 value = _x(value)
31 elif type(self.data) == dict:
32 value = self.__getattr__(item)
33 return value