Skip to content Skip to sidebar Skip to footer

Python: Adding To Dict Of One Object In A List Changes All Dicts Of Every Other Object In The List

So Python isn't my strong suit and I've encountered what I view to be a strange issue. I've narrowed the problem down to a few lines of code, simplifying it to make asking this que

Solution 1:

The reason for this is because drugs is a class attribute. So if you change it for one object it will in fact change in others.

If you are looking to not have this behaviour, then you are looking for instance attributes. Set drugs in your __init__ like this:

classFinalRecord():def__init__(self):
        self.ruid = 0self.drugs = {}

Take note of the use of self, which is a reference to your object.

Here is some info on class vs instance attributes

So, full demo illustrating this behaviour:

>>>classFinalRecord():...def__init__(self):...        self.ruid = 0...        self.drugs = {}...>>>obj1 = FinalRecord()>>>obj2 = FinalRecord()>>>obj1.drugs['stuff'] = 2>>>print(obj1.drugs)
{'stuff': 2}
>>>print(obj2.drugs)
{}

Solution 2:

You define drugs as a class attribute, not an instance attribute. Because of that, you are always modifying the same object. You should instead define drugs in the __init__ method. I would also suggest using ruid as an argument:

classFinalRecord():def__init__(self, ruid):
        self.ruid = ruid
        self.drugs = {}

It could then be used as this:

fr = FinalRecord(7)
finalRecords.append(fr)
fr2 = FinalRecord(10)
finalRecords.append(fr2)

Or more simply:

finalRecords.append(FinalRecord(7))
finalRecords.append(FinalRecord(10))

Post a Comment for "Python: Adding To Dict Of One Object In A List Changes All Dicts Of Every Other Object In The List"