我需要找出給定命名元組是否存在於命名元組列表中(命名元組是指例如'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)
你應該發佈'pt'看起來像你如何定義你的命名元組。 – khachik
歡迎來到StackOverflow。請閱讀並遵守幫助文檔中的發佈準則。 [最小,完整,可驗證的示例](http://stackoverflow.com/help/mcve)適用於此處。具體而言,您沒有發佈重現問題的代碼。 – Prune
,並且'isThere'中的循環沒有任何意義。 – khachik