2013-12-17 46 views

回答

0
class Vector(): 

    def __init__(self, *args): 
     self.args = args 

    def __add__(self, other): 
     return tuple(map(lambda x:x+other,self.args)) 

a = Vector(1,2,3,4,5) 
print a+3 
+0

你好,非常感謝。我也嘗試這個,它也工作得很好。 –

+0

不客氣:) – sinceq

2

這裏有一個簡單的實現:

class vector(object): 

    def __init__(self, *args): 
     self.args = args 

    def __add__(self, other): 
     if not isinstance(other, int): 
      raise TypeError("Cannot add {} with {}".format(type(self), type(other))) 
     return vector(*(arg + other for arg in self.args)) 

    def __repr__(self): 
     return "vector({})".format(", ".join(map(str, self.args))) 


a = vector(7, 4, 2) 

print a + 3 # (10, 7, 5) 

輸出:

vector(10, 7, 5) 

我以爲你(10, 7, 4)本來是(10, 7, 5)

+1

我建議實現'__str__'而不是'__repr__'。 'repr'類似於內置類型的類可能令人難以置信地被檢測到。 – user2357112

+0

啊,是的好點。讓我解決這個問題! –

+0

你好!非常感謝您的幫助。這段代碼工作得很好。也感謝您使用\ __ repr__,我也會使用它。我是python類的新手。再次感謝你的幫助。 –

相關問題