实现一个ordeeddict

class MyOrderdict():
def __init__(self, mydict):
self._cur = 0
self._mykeys = []
self._myvalues = []
self._mydict = mydict
for i in mydict:
self._mykeys.append(i[0])
self._myvalues.append(i[1])

def keys(self):
return self._mykeys

def values(self):
return self._myvalues

def items(self):
return self._mydict

def __getitem__(self, item):
if item not in self._mykeys:
raise ValueError
return self._myvalues[self._mykeys.index(item)]

def __setitem__(self, key, value):
self._mykeys.append(key)
self._myvalues.append(value)

def __getattr__(self, item):
if item not in self._mykeys:
raise ValueError
return self._myvalues[self._mykeys.index(item)]

def __iter__(self):
return self

def __next__(self):
self._cur += 1
if self._cur > len(self._mykeys):
self._cur = 0
raise StopIteration
return (self._mykeys[self._cur - 1], self._myvalues[self._cur - 1])

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

def __str__(self):
return str(self._mydict)

a = MyOrderdict([('a', 1), ('b', 2)])
a.a
a['a']
a.keys()
a.values()
len(a)
for i in a:
  print(i)
for i in a.items():
  print(i)

posted on 2018-04-26 11:18 跑跑兔 阅读() 评论() 编辑 收藏

版权声明:本文为EmptyRabbit原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/EmptyRabbit/p/8950377.html