Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #20684
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Subject | Re: Inheriting from OrderedDict causes problem |
| Followup-To | gmane.comp.python.general |
| Date | 2012-02-22 18:10 +0100 |
| Organization | None |
| References | <a1d845b2-7aaa-4696-8a65-fb36bb73f164@f5g2000yqm.googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.45.1329930613.3037.python-list@python.org> (permalink) |
Followups directed to: gmane.comp.python.general
Bruce Eckel wrote:
> Notice that both classes are identical, except that one inherits from
> dict (and works) and the other inherits from OrderedDict and fails.
> Has anyone seen this before? Thanks.
>
> import collections
>
> class Y(dict):
> def __init__(self, stuff):
> for k, v in stuff:
> self[k] = v
>
> # This works:
> print Y([('a', 'b'), ('c', 'd')])
>
> class X(collections.OrderedDict):
> def __init__(self, stuff):
> for k, v in stuff:
> self[k] = v
>
> # This doesn't:
> print X([('a', 'b'), ('c', 'd')])
>
> """ Output:
> {'a': 'b', 'c': 'd'}
> Traceback (most recent call last):
> File "OrderedDictInheritance.py", line 17, in <module>
> print X([('a', 'b'), ('c', 'd')])
> File "OrderedDictInheritance.py", line 14, in __init__
> self[k] = v
> File "C:\Python27\lib\collections.py", line 58, in __setitem__
> root = self.__root
> AttributeError: 'X' object has no attribute '_OrderedDict__root'
> """
Looks like invoking OrderedDict.__init__() is necessary:
>>> from collections import OrderedDict
>>> class X(OrderedDict):
... def __init__(self, stuff):
... super(X, self).__init__()
... for k, v in stuff:
... self[k] = v
...
>>> X([("a", "b"), ("c", "d")])
X([('a', 'b'), ('c', 'd')])
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Inheriting from OrderedDict causes problem Bruce Eckel <lists.eckel@gmail.com> - 2012-02-22 08:53 -0800
Re: Inheriting from OrderedDict causes problem Peter Otten <__peter__@web.de> - 2012-02-22 18:10 +0100
Re: Inheriting from OrderedDict causes problem Bruce Eckel <lists.eckel@gmail.com> - 2012-02-22 09:33 -0800
csiph-web