Search code examples
pythonconstructor

Can someone explain the difference between the two and why one produces a wrong result; Python instance variables


Maybe a very noob question but the below gives wrong results when vecDict is initialized outside of init. Can someone please explain why..

class Vector:
    #vecDict = {} ## vecDict declared here gives wrong results vs in the init method.
    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.vecDict = {}
        for i in range(len(nums)):
            self.vecDict[i]=nums[i]
 
    def getDict(self):
        return self.vecDict

    # Return the dotProduct of two sparse vectors
    def dotProduct(self, vec):
        print(vec.getDict())
        print(vec.vecDict)
        """
        :type vec: 'SparseVector'
        :rtype: int
        """
        # print(vec.getDict())
        dotProd = 0
        secDict = vec.getDict()
        for k in secDict:
            if k in self.vecDict:
                dotProd += (self.vecDict[k] * secDict[k])

        # print(self.vecDict)
        # print(secDict)

        return dotProd 

Vector object will be instantiated and called as:

v1 = Vector(numsA)
v2 = Vector(numsB)
ans = v1.dotProduct(v2) 

Ex input: numsA = [1,0,0,2,3]

numsB = [0,3,0,4,0]

ans = 8


Solution

  • The way you're declaring your variable outside of the init it is a class variable and therefore its value is shared by all instances of that respective class.

    If you want it to be individual for every instance you have to place it inside the init and assign via the keyword self to the respective instance of the class.

    https://pynative.com/python-class-variables/