1
class SortedDict(dict):
    def __init__(self, data=None):
        if data is None:
            data = {}
        super(SortedDict, self).__init__(data)

and

class SortedDict(dict):
    def __init__(self, data={}):
        dict(data)

I think they are same.

Asaph
  • 159,146
  • 25
  • 197
  • 199
zjm1126
  • 63,397
  • 81
  • 173
  • 221

2 Answers2

5

dict(data) just creates a dictionary from data without saving the result anywhere. super(SortedDict, self).__init__(data) on the other hand calls the parent class constructor.

Also, in the case of multiple inheritance, using super ensures that all the right constructors are called in the right order. Using None as a default argument instead of a mutable {} ensures that those other constructors don't accidentally modify SortedDicts default argument.

Community
  • 1
  • 1
sth
  • 222,467
  • 53
  • 283
  • 367
1

The first class doesn't seem to work

class SortedDict2(dict):
    def __init__(self, data={}):
        dict(data)

class SortedDict(dict):
    def __init__(self, data=None):
        if data is None:
            data = {}
        super(SortedDict, self).__init__(data)



x = SortedDict2("bleh")
y = SortedDict({1: 'blah'})

print x
print y

File "rere.py", line 3, in __init__
 dict(data)
ValueError: dictionary update sequence element #0 has length 1; 2 is required


x = SortedDict2({1: "bleh"})
y = SortedDict({1: 'blah'})

print x
print y

>> {}
>>{1: 'blah'}
Steven Sproat
  • 4,398
  • 4
  • 27
  • 40