Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading