2011-10-07 58 views
0

我的一個練習說寫一個添加方法與一個Point對象或元組的工作要點:與一個Point對象或元組工作Add方法

  • 如果第二個操作數是一個Point,該方法應該返回一個新的Point,其x座標是操作數的x座標之和,同樣也是y座標。
  • 如果第二個操作數是一個元組,則該方法應該將元組的第一個元素添加到x座標,將第二個元素添加到y座標,並返回一個帶有結果的新Point。

這是多遠,我不知道我的代碼的元組部分是否準確。有人可以澄清一下我如何將這個程序稱爲元組部分。我想我釘了第一部分。

這裏是我的代碼:

Class Point(): 
    def__add__(self,other): 
      if isinstance(other,Point): 
        return self.add_point(other) 
      else: 
        return self.print_point(other) 

    def add_point(self,other): 
      totalx = self.x + other.x 
      totaly = self.y + other.y 
      total = ('%d, %d') % (totalx, totaly) 
      return total 

    def print_point(self): 
      print ('%d, %d) % (self.x, self.y) 

    blank = Point() 
    blank.x = 3 
    blank.y = 5 
    blank1 = Point() 
    blank1.x = 5 
    blank1.y = 6 

這是我到目前爲止已經建成,我不知道如何與實際元組的部分運行此。我知道它是否blank + blank1 if部分會運行並調用add_point函數,但是如何啓動元組。我不確定我是否正確寫下了這個...請協助。

回答

1

另外,如果你希望能夠使用point.x和point.y語法,你可以實現如下:

class Point(): 
    def __init__(self, x, y): 
     self.x = x 
     self.y = y 

    def __add__(self, other): 
     if isinstance(other, Point): 
      return Point(self.x + other.x, self.y + other.y) 
     elif isinstance(other, tuple): 
      return Point(self.x + other[0], self.y + other[1]) 
     else: 
      raise TypeError("unsupported operand type(s) for +: 'Point' and '{0}'".format(type(other))) 

    def __repr__(self): 
     return u'Point ({0}, {1})'.format(self.x, self.y) #Remove the u if you're using Python 3 
+0

你能解釋一點點的elif的isinstance(其他,元組)?這個回報,請解釋一下,如果我們放置一個元組,那會是什麼樣子? –

+0

這個add方法首先檢查傳入的參數是否是一個Point,如果不是,它是否是一個元組。在這兩種情況下,我們用相應的座標(分別是x和y的總和,或者使用元組的第一個和第二個元素作爲z和y)實例化一個新點。 –

+1

無論如何,我都會從一個元組繼承,並且使x ''''''''屬性 –

2

你可以簡單地從元組中派生你的類(或者只是實現__getitem__)。

class Point(tuple): 
    def __new__(cls, x, y): 
     return tuple.__new__(cls, (x, y)) 

    def __add__(self, other): 
     return Point(self[0] + other[0], self[1] + other[1]) 

    def __repr__(self): 
     return 'Point({0}, {1})'.format(self[0], self[1]) 

p = Point(1, 1) 
print p + Point(5, 5) # Point(6, 6) 
print p + (5, 5)  # Point(6, 6) 
相關問題