简体   繁体   中英

How do I find objects from child class by attribute in Python

Let's say I have the following classes defined to construct a building made of rectangles which are made from points. How do I query all the rectangles by attribute from inside a Building class? I think I'm supposed to use a super method here but after reading online, cannot figure it out. Thank you.


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)

Your inheritance make no sense. Buildings are not rectangles, and rectangles are not points. This is a job for composition, not inheritance, and you're correctly doing that by passing in the points etc - just leave off the inheritance.

Apart from that, I'm not sure what your question is. There's no way to query attributes other than iterating through, which you're already doing, unless you store then in some kind of data structure that indexes the attribute you want to query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM