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

后端 未结 2 796
难免孤独
难免孤独 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:37

    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:

    class FinalRecord():
        def __init__(self):
            self.ruid = 0
            self.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:

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

提交回复
热议问题