设置类属性的默认值时的行为

时间:2018-10-26 00:39:39

标签: python-3.x

我无法理解我所看到的行为是否是预期的,为什么会这样,或者是否还有其他事情发生。

在下面的示例中将列表默认分配给类属性d和v时,看起来好像是在对象范围之外访问这些列表...如果我在此处遗漏某些东西,请纠正我

List

当我避免在kwargs中设置d和v的默认值时,我看不到这一点...

Class RandomTest:
    def __init__(self, d=[], v=[]):
        self.d = d
        self.v = v
    def add(self, d, v):
        self.d.append(d)
        self.v.append(v)

my_dict = {}

for x in range(100):
    if str(x) not in my_dict:
        my_dict[str(x)] = RandomTest()
    my_dict[str(x)].add(str(x), x)

print(my_dict['1'].d)

['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', 
'14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', 
'26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', 
'38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', 
'50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', 
'62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', 
'74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', 
'86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', 
'98', '99']

0 个答案:

没有答案