2016-10-10 67 views
-1

我需要找出給定命名元組是否存在於命名元組列表中(命名元組是指例如'Polygon'中的A(2,3)類)。如果給定的元組不在列表中,我們將元組附加到列表中。如果它存在,則引發用戶定義的異常。該功能在列表中不存在給定點時起作用。但是,如果這個觀點確實存在,那麼就不會出現異常,並且它會再次添加到列表的末尾。這裏是我到目前爲止有: 類ExistingPointError(例外): DEF 初始化(個體經營,價值): self.value = 0在命名元組列表中搜索命名元組

class Polygon(object): 
    counter = 0 
    def __init__(self): 
     Polygon.counter+=1 
     self.points = [] 


# and here's the function that I'm working with 

    def setter(self,pt): 
     def isThere(pt): 
       if pt in self.points: raise ExistingPointError() 

      print("Setting Point") 
     try: 
      isThere(pt) 
      self.points.append(pt) 
     except ExistingPointError as E: 
      print("Point exists! value: ", E) 
     print(self.points) 


P = Polygon() 
point=collections.namedtuple('PointName','Name x y') 
A = point(Name = 'A', x = 5, y = 0) 
B = point(Name = 'B',x = 10,y = 5) 
C = point(Name = 'C',x=5,y=10) 
D = point(Name = 'D', x=-2,y=8) 
lst = [A,B,C,D] 
P.createPolygon(lst) 
P.setter(D) 
+0

你應該發佈'pt'看起來像你如何定義你的命名元組。 – khachik

+0

歡迎來到StackOverflow。請閱讀並遵守幫助文檔中的發佈準則。 [最小,完整,可驗證的示例](http://stackoverflow.com/help/mcve)適用於此處。具體而言,您沒有發佈重現問題的代碼。 – Prune

+1

,並且'isThere'中的循環沒有任何意義。 – khachik

回答

0

這個怎麼樣?

def setter(self,pt): 
    def isThere(pt): 
     if pt in self.points: 
      raise ExistingPointError() 
     print("Setting Point") 
    try: 
     isThere(pt) 
     self.points.append(pt) 
    except ExistingPointError as E: 
     print("Point exists! value: ", E) 
    print(self.points) 

但我不確定是否有例外,也許試試這個:

def setter(self,pt): 
    if pt in self.points: 
     print("Point exists!") 
    else: 
     self.points.append(pt) 
    print(self.points) 
+0

我以前試過這個,給我同樣的答案:( – Shruthi

+0

看到的東西是你的for循環沒有任何意義,並且不需要異常。你確定點是相同的嗎?(一個命名的元組不同於常規元組) – 2016-10-10 17:52:15

+0

是的,我嘗試了沒有for循環,我得到了相同的答案。所有的點都被命名爲元組:L這是一個實驗室任務,所以問題說明我必須使用異常 – Shruthi

0

你想提出一個用戶定義的錯誤ExistingPointError(),但你還沒有真正定義它是什麼。當我運行代碼,並插入重複解析成一個多邊形對象,我得到以下錯誤:

Traceback (most recent call last): 
File "python", line 27, in <module> 
File "python", line 20, in setter 
NameError: name 'ExistingPointError' is not defined 

您可能不需要爲@Gjhuizing提到引發異常這一點。告訴用戶該對象已經存在的簡單消息應該足以滿足您的需求。