Python: Adding to dict of one object in a list changes all dicts of every other object in the list

后端 未结 2 812
难免孤独
难免孤独 2021-01-20 21:51

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 askin

2条回答
  •  我在风中等你
    2021-01-20 22:25

    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:

    class FinalRecord():
        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))
    

提交回复
热议问题