0
比方說,我定義了以下類來構造由矩形構成的建築物,這些矩形由點組成。如何通過Building類中的屬性查詢所有矩形?我想我應該在這裏使用一種超級方法,但在網上閱讀後,無法弄清楚。謝謝。如何通過Python中的屬性查找子類中的對象
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Rectangle(Point):
def __init__(self, north, east, south, west):
self.north = north
self.east = east
self.south = south
self.west = west
class Building(Rectangle):
def __init__(self, rectangles):
self.rectangles = rectangles
#Search through all the points to find one with matching attributes
def find_point_by_elevation(self, y):
for rectangle in self.rectangles:
if rectangle.south.y = y:
return rectangle.south
#Testing the Code
n, e, s, w = Point(1,2), Point(2,1), Point(0,1), Point(0,1)
rectangle1 = Rectagnle(n,e,s,w)
n, e, s, w = Point(10,20), Point(20,10), Point(0,10), Point(0,10)
rectangle2 = Rectagnle(n,e,s,w)
my_building = [rectangle1, rectangle2]
my_building.find_point_by_elevation(1)
丹尼爾,謝謝你幫助我。我覺得沒有意識到這不是一個繼承問題。我想這個數據結構將類似於Django中的多對一關係。再次感謝。 – JasonArg123 2013-03-14 16:51:32