我需要找出命名元组列表中是否存在给定的命名元组(命名元组是'Polygon'类中的点,例如A(2,3))。如果列表中不存在给定的元组,我们将元组追加到列表中。如果它存在,则引发用户定义的异常。当列表中不存在给定点时,该功能有效。但是,如果该点确实存在并且它只是再次添加到列表的末尾,则不会引发异常。这是我到目前为止所拥有的: class ExistingPointError(Exception): def init (self,value): 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 :(得分: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)
答案 1 :(得分:0)
您想要引发用户定义的错误,ExistingPointError(),但您还没有真正定义它是什么。当我运行您的代码并将重复的元组插入Polygon对象时,我收到以下错误:
Traceback (most recent call last):
File "python", line 27, in <module>
File "python", line 20, in setter
NameError: name 'ExistingPointError' is not defined
你可能不需要像@Gjhuizing所提到的那样引发异常。告诉用户该对象已经存在的简单消息应该足以满足您的需求。