Reputation: 66677
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.
Upvotes: 1
Views: 119
Reputation: 229663
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 SortedDict
s default argument.
Upvotes: 5
Reputation: 4578
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'}
Upvotes: 1