는 Foo.__contains__
는 정의되지 않은 경우 : 012 이후
def __setitem__(self, key, value, PREV=0, NEXT=1, dict_setitem=dict.__setitem__):
'od.__setitem__(i, y) <==> od[i]=y'
# Setting a new item creates a new link at the end of the linked list,
# and the inherited dictionary is updated with the new key/value pair.
if key not in self:
root = self.__root
last = root[PREV]
last[NEXT] = root[PREV] = self.__map[key] = [last, root, key]
dict_setitem(self, key, value)
이 이런 식으로 정의된다 OrderedDict.__setitem__
를 호출
self[key] = data
실행
a['bar']
통화 Foo.__getitem__
,이 정의되어 있지 않습니다.
if key not in self:
이 참입니다. 따라서 키는 self.__root
및 self.__map
에 올바르게 추가됩니다. Foo.__contains__
가을 정의
, 거짓 경우
if key not in self:
. 따라서 키가 self.__root
및 self.__map
에 올바르게 추가되지 않았습니다. Foo.__contains__
효과적인 바보 OrderedDict.__setitem__
은 이미 'bar'
키가 추가되었다고 생각합니다.
나는 것이 도움 (인쇄 __setitem__
에서 제표 및 __iter__
추가) 다음 코드로 연주 발견 : 당신이 Foo
의 서브 클래스를 만들어이 문제를 방지 할 수 있습니다
from collections import OrderedDict
dictclass = OrderedDict
class Foo(dictclass):
def __getitem__(self,key):
try:
return dictclass.__getitem__(self,key)
except KeyError:
pass
data = key*2
self[key] = data
return data
def __contains__(self,whatever):
print('contains: {}'.format(whatever))
return dictclass.__contains__(self,whatever) or 'bar' in whatever
def __setitem__(self, key, value, PREV=0, NEXT=1, dict_setitem=dict.__setitem__):
'od.__setitem__(i, y) <==> od[i]=y'
# Setting a new item creates a new link at the end of the linked list,
# and the inherited dictionary is updated with the new key/value pair.
print('key not in self: {}'.format(key not in self))
if key not in self:
root = self._OrderedDict__root
last = root[PREV]
last[NEXT] = root[PREV] = self._OrderedDict__map[key] = [last, root, key]
dict_setitem(self, key, value)
def __iter__(self):
'od.__iter__() <==> iter(od)'
# Traverse the linked list in order.
NEXT, KEY = 1, 2
root = self._OrderedDict__root
curr = root[NEXT]
print('curr: {}'.format(curr))
print('root: {}'.format(root))
print('curr is not root: {}'.format(curr is not root))
while curr is not root:
yield curr[KEY]
curr = curr[NEXT]
a = Foo()
print a['bar']
# barbar
print a.keys()
# ['bar']
공지 사항 collections.MutableMapping
이고 대부분의 동작을 OrderedDict
속성에 위임합니다.
심지어 정의 __contains__
와 a = Foo()
print a['bar']
# barbar
print a.keys()
# ['bar']
을 수득
.
나는 [출처] (http://hg.python.org/cpython/file/2.7/Lib/collections.py)를 읽고 있는데, 나는이 것을 알아 내기 힘들다. – mgilson
나는 그렇게하고 있는데, 나는 어디에서 문제인지 생각한다 :'__setitem__'과'__iter__'을 한번보세요. –
@A.Rodas - 예, 그것이 내가보고있는 곳입니다. 어쩌면 너무 피곤할 지 모르지만 나는 모든 논리를 똑바로 유지하는 데 어려움을 겪고있었습니다. – mgilson