I have two classes, a main class which creates instances of my other class.
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
The issue I'm having has to do with the attrs
dictionary that gets passed to the Thing
class. The problem is that each time I use the Builder
class to create a Thing
class, the attrs argument retains it's previous values
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']}
My Question is 2 part:
Why is this happening?
How do I fix it?