让我们说我已经定义了以下类来构建由矩形构成的建筑物。如何从Building类中查询属性的所有矩形?我想我应该在这里使用超级方法,但在网上阅读后,无法弄明白。谢谢。
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)
答案 0 :(得分:1)
你的继承毫无意义。建筑物不是矩形,矩形不是点。这是一个组合工作,而不是继承,你通过传递点等正确地做到这一点 - 只是放弃继承。
除此之外,我不确定你的问题是什么。除非您将某个数据结构存储在索引要查询的属性的数据结构中,否则无法查询除迭代之外的属性,除非您已经在进行查询。