Inheriting from OrderedDict causes problem

B

Bruce Eckel

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'
"""
 
P

Peter Otten

Bruce said:
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:
.... def __init__(self, stuff):
.... super(X, self).__init__()
.... for k, v in stuff:
.... self[k] = v
....
X([('a', 'b'), ('c', 'd')])
 
B

Bruce Eckel

Looks like invoking OrderedDict.__init__() is necessary:

...     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')])

Thank you! That worked. Languages. Some of them automatically call the
default base-class constructors, others don't. Apparently.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top