将管理矩形的功能(访问、添加或删除它们)与成为矩形的想法结合起来并不是一个好主意。您永远不知道何时可能需要维护多个列表,或从无序列表更改为有组织的列表。
在您真的需要更多之前,请保持管理功能简单:使用内置列表或字典。如果您只关心订购,或者只需要知道您有一堆东西,请使用列表:
class Rectangle (object):
def __init__(self, top, bottom, left, right):
self.Top = top
self.Left = left
self.Right = right
self.Bottom = bottom
list_of_rects = [Rectangle(10,0,0,10), Rectangle(20, 10, 10 ,20)]
# how many rects?
len(list_of_rects)
# result: 2
# where is this particular rect?
fred = Rectangle(30,20,20, 30)
list_of_rects.insert(fred, 1)
list_of_rects.index(fred)
# result: 1
#remove an item from the list:
list_of_rects.remove(fred)
#search the list:
right_of_5 = [rect for rect in list_of_rects if rect.Left > 5]
如果您出于某种原因需要访问各个矩形——“目标的矩形是什么”之类的——你有两个选择:
1)需要 rect 的代码只保留对它的引用:
class Goal(object):
def __init__(self, rect):
self.Rect = rect
goalrect = Rectangle (0,0,20,20)
mygoal = Goal(goalrect)
list_of_rects.append(goalrect)
# now goalrect always knows about it's own rect, but the list can keep track of it too...
2)或者,使用字典:
named_rects = {}
named_rects['goal'] = Rectangle(0,0,20,20)
使用字典可以获得与使用列表相同的所有功能——添加、删除和查找——除了字典不保留顺序,因此你无法管理诸如优先级之类的事情:
# add to the dict:
named_rects['new_rect'] = Rectangle(90,90,95,95)
# remove
del named_rects['new_rect']
# find = is there a known key?
if 'new_rect' in named_rects: print new_rect
# search:
right_of_5 = [rect for rect in named_rects.items() if rect.Left > 5]
在某些情况下,您需要比普通的旧列表和字典更高级的东西——但总是先尝试免费的东西:)