Ryan Mattox
Ryan Mattox

Reputation: 13

How to prevent reassignment of variable to object of same class from keeping previous data?

When reassigning box with a new instance of Box, instead of self.things being assigned an empty dictionary, it contains the same data from the previous instance.

I'm using python 3.7.3

import random

class Box:
    def __init__(self, things = {}):
        self.things = things

    def __str__(self):
        return str(self.things)

    def put_thing_in_location(self, thing, location):
        self.things[location] = thing


for i in range(2):
    box = Box()
    print(box)
    box.put_thing_in_location(
        random.randrange(10000), 
        random.randrange(10000)
    )

Output:

$ python bugTest.py

{}

{652: 8968}

I expect that things of the new instance of Box be an empty dictionary if no arguments are passed to it. Instead it keeps things from the previous instance of Box.

Upvotes: 1

Views: 1154

Answers (2)

Sunitha
Sunitha

Reputation: 12015

When you define the function def __init__(self, things = {}):, things gets initialized to an empty dict and whenever __init__ gets invoked, the same dict (which might not be empty when you invoke it second time) would be passed, when you dont explicitly specify an value for things

def __init__(self, things = None):
     things = things or {}
     ... 

Upvotes: 0

donkopotamus
donkopotamus

Reputation: 23176

The issue is that you are assigning the exact same dictionary as the default to your instances, thus sharing it across all instances. Change your constructor to

def __init__(self, things=None):
    self.things = {} if things is None else things

This ensures that each instance takes a fresh dictionary as the default if nothing is given.

Upvotes: 1

Related Questions