我有两个类,一个主类,它创建我的另一个类的实例。
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部分:
为什么会这样?
我如何解决它?
大话西游666
相关分类