Skip to content Skip to sidebar Skip to footer

Python Class Instance Vs. Class Variables

I am trying to define a list as an instance variable within a class but it is acting as a class variable. class THING: def __init__(self, name, stuff): self.name = name

Solution 1:

When you are passing datecnts list to your THING object's constructor, you are just passing the reference (and list is mutable and dict are mutable) , hence if you make any changes to the dict for A THING object, it would reflect in B , since B also has the same reference. You should try to do copy.deepcopy of datecnts and send that to A and B separately.

Example -

importcopy
list.append(THING('A', copy.deepcopy(datecnts)))
list.append(THING('B', copy.deepcopy(datecnts)))

Post a Comment for "Python Class Instance Vs. Class Variables"