Search code examples
pythonclassinstance

Python: Objects initialized the same way affect each other


I'm creating a class like the following in Python:

stat_list = ['Health', 'Strength', 'Stamina']

empty_stats = dict.fromkeys(stat_list, 0)


class Stats:
    def __init__(self, stat_dict=None):
        if stat_dict is None:
            stat_dict = empty_stats
        self.stat_dict = stat_dict
        self.fill_stat_dict()

    def fill_stat_dict(self):
        for stat in stat_list:
            if stat not in self.stat_dict:
                self.stat_dict[str(stat)] = 0

    def increase_stat(self, stat, amount):
        if stat in self.stat_dict.keys():
            self.stat_dict[stat] += amount

    def sum_stat(self):
        return sum(self.stat_dict.values())

So far, so good, but I bumped into the following issue:

blank1 = Stats()
print(blank1.sum_stat())

blank2 = Stats()
print(blank2.sum_stat())

not_blank = Stats({'Stamina': 4})
print(not_blank.sum_stat())

blank2.increase_stat('Health', 2)
print(blank1.sum_stat())
print(blank2.sum_stat())
print(not_blank.sum_stat())

output: 0 0 4 2 2 4

I would want blank1 and blank2 to be separate objects of the Stats class initially created empty that can be modified independently. But what I'm seeing here is that modifying blank1 affects blank2, while not_blank remains independent. What am I doing wrong?


Solution

  • dictionary's are passed by reference which means that empty_stats is being modified by Stats, try changing the line so that it makes a new copy

    ...
        def __init__(self, stat_dict=None):
            if stat_dict is None:
                stat_dict = empty_stats.copy()# <- change this
            self.stat_dict = stat_dict
            self.fill_stat_dict()
    ...