我有两个类,一个主类,它创建我的另一个类的实例。class Builder: def __init__(self, id): self.id = id def build_thing(self, main_ftr, main_attr, attrs = {}): # note the main ftr/attrs gets added to attrs no matter what attrs[main_ftr] = attrs.get(main_ftr, []) + [main_attr] return Thing(main_ftr, main_attr, attrs)class Thing: def __init__(self, main_ftr, main_attr, attrs): self.main_ftr = main_ftr self.main_attr = main_attr self.attrs = attrs我遇到的问题与attrs传递给Thing该类的字典有关。问题是每次我使用Builder该类创建一个Thing类时, attrs 参数都会保留它以前的值b = Builder('123')t = b.build_thing('name', 'john')print(t.attrs) # {'name': ['john'] }# Goal is this creates a new "Thing" with only attrs = {'name':['mike']}t2 = b.build_thing('name', 'mike')print(t2.attrs) # {'name': ['john', 'mike']}我的问题是2部分:为什么会这样?我如何解决它?
1 回答
大话西游666
TA贡献1817条经验 获得超14个赞
函数的可选参数被初始化一次。由于attrs是可变的,每次调用该函数时,都会向该字典添加新的键值对,并保留它以供进一步调用。如果您需要可变数据结构作为默认参数,请使用类似以下内容的方法:
def build_thing(self, main_ftr, main_attr, attrs=None):
if attrs is None:
attrs = {}
attrs[main_ftr] = attrs.get(main_ftr, []) + [main_attr]
return Thing(main_ftr, main_attr, attrs)
添加回答
举报
0/150
提交
取消