有人可以解释两者之间的区别以及为什么会产生错误的结果吗? Python 实例变量

问题描述 投票:0回答:1

也许是一个非常菜鸟的问题,但是当 vecDict 在 init 之外初始化时,下面给出了错误的结果。有人可以解释一下为什么吗..

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 

矢量对象将被实例化并调用为:

v1 = SparseVector(numsA)

v2 = SparseVector(numsB)

ans = v1.dotProduct(v2)

python constructor
1个回答
0
投票

您在 init 之外声明变量的方式是,它是一个类变量,因此它的值由相应类的所有实例共享。

© www.soinside.com 2019 - 2024. All rights reserved.