-1

Why am I getting the previous value into the different instance variables?

For example:

d1 = myDict()
d2 = myDict()
d1.assign(2,3)
d2.assign(2,2)
print(d1.getval(2))
print(d2.getval(2))
class myDict(object):
    """ Implements a dictionary without using a dictionary """
    aDict = {}
    def __init__(self):
        """ initialization of your representation """
        #FILL THIS IN

    def assign(self, k, v):
        """ k (the key) and v (the value), immutable objects  """
        #FILL THIS IN
        self.k = k
        self.v = v
        if self.k not in myDict.aDict:
            self.aDict[self.k] = self.v
        else:
            self.aDict[self.k] = self.v

    def getval(self, k):
        """ k, immutable object  """
        #FILL THIS IN

        if k in myDict.aDict:
            return myDict.aDict[k]
        else:
            KeyError ('KeyError successfully raised')

        # return myDict.aDict[k]

    def delete(self, k):
        """ k, immutable object """   
        #FILL THIS IN
        if k in myDict.aDict.keys():

            del myDict.aDict[k]
        else:
            raise KeyError('KeyError successfully raised')

    def __str__(self):
        return str(myDict.aDict)



d1 = myDict()
d2 = myDict()
d1.assign(2,3)
d2.assign(2,2)
print(d1.getval(2))
print(d2.getval(2))

My output:

2
2
4
1

Correct output:

3
2
4
1
Diptangsu Goswami
  • 5,554
  • 3
  • 25
  • 36
code_conundrum
  • 529
  • 6
  • 12

2 Answers2

4

aDict has been defined as a class level attribute, this means that all instances of myDict will share the same aDict.

To assign a separate aDict for each instance you should do this in the __init__ method

def __init__(self):
    self.aDict = {}
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50
  • You are awesome bro. I finally made the full grade in the course. because of this small problem, I was losing 6 points. Thank you so much! – code_conundrum Aug 03 '19 at 17:15
1

It looks like aDict is not an instance variable, but a static variable. This means there exists only one aDict instance on a class-level which is shared by all instances of your myDict class. As a result, any changes you make to aDict in any given myDict instance will be reflected in all myDict instances.

In addition, I'd like to point out that you're not following the instructions of the assignment. The docstring of your class says you must implement this class without using a dictionary.

Paul M.
  • 10,481
  • 2
  • 9
  • 15