2016-10-16 151 views
0
class MyVector: 
    def __init__(self, vector): # classic init 
     self.vector = vector 

    def get_vector(self): 
     return self.vector 

    def __mul__(self, other): 
     for i in range(0, len(self.vector)): #cycle 
      # if I did scalar_product += (self.vector[i] * other.vector[i]) here, 
      # it didn't work 
      scalar_product = (self.vector[i] * other.vector[i]) 
     return (scalar_product)  

if __name__ == "__main__":  #just testing program 
    vec1 = MyVector([1, 2, 3, 4]) 
    vec2 = MyVector([4, 5, 6, 7]) 
    print(vec1.get_vector()) 
    print(vec2.get_vector()) 
    scalar_product = vec1*vec2 
    print(scalar_product) # shows only 4*7 but not others 

爲了使該程序有效,我需要做些什麼?現在它只是乘以最後的數字,例如4 * 7,而不是其他數字。類向量 - 兩個非特定維向量的乘法運算

回答

1

您需要先定義你的標產品:

def __mul__(self, other): 
    scalar_product = 0 # or 0.0 
    for i in range(0, len(self.vector)): 
     scalar_product += self.vector[i] * other.vector[i] 
    return scalar_product 

你也應該返回類型MyVector

+0

的目標謝謝我的朋友。 –

+0

現在我覺得很愚蠢:D –