[英]How do I find objects from child class by attribute in Python
假設我定義了以下類,以構造由點組成的矩形構成的建築物。 如何從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)
您的繼承毫無意義。 建築物不是矩形,矩形也不是點。 這是用於合成的工作,而不是繼承,您通過傳遞要點等來正確地做到這一點-只需放棄繼承即可。
除此之外,我不確定您的問題是什么。 除了已經遍歷之外,沒有其他方法可以查詢屬性,除非您將其存儲在某種數據結構中,該數據結構為要查詢的屬性編制了索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.