【发布时间】:2020-12-24 19:41:18
【问题描述】:
下面两个类定义有什么区别,
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
【问题讨论】:
-
注意,
self = whatever可能没有按照您的想法行事。self只是__init__函数中的一个局部变量,它不是魔法,也不会改变你的实例。因此,您只需将传入的dict分配给局部变量self。
标签: python python-class