class SortedDict(dict):
def __init__(self, data=None):
if data is None:
data = {}
super(SortedDict, self).__init__(data)
和
class SortedDict(dict):
def __init__(self, data={}):
dict(data)
我认为它们是一样的。
答案 0 :(得分:5)
dict(data)
只需从data
创建一个字典,而无需将结果保存在任何位置。另一方面,super(SortedDict, self).__init__(data)
调用父类构造函数。
此外,在多重继承的情况下,使用super
可确保以正确的顺序调用所有正确的构造函数。使用None
作为默认参数而不是可变{}
可确保其他构造函数don't accidentally modify SortedDict
s default argument。
答案 1 :(得分:1)
第一堂课似乎不起作用
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'}