下面的两个类定义有什么区别,
class my_dict1(dict):
def __init__(self, data):
self = data.copy()
self.N = sum(self.values)
上面的代码结果AttributeError: 'dict' object has no attribute 'N'
,而下面的代码编译
class my_dict2(dict):
def __init__(self, data):
for k, v in data.items():
self[k] = v
self.N = sum(self.values)
例如,
d = {'a': 3, 'b': 5}
a = my_dict1(d) # results in attribute error
b = my_dict2(d) # works fine