【问题标题】:How do I find objects from child class by attribute in Python如何在 Python 中按属性从子类中查找对象
【发布时间】:2013-03-14 15:41:42
【问题描述】:

假设我定义了以下类来构建由点组成的矩形组成的建筑物。如何从 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)

【问题讨论】:

    标签: python object inheritance child-objects


    【解决方案1】:

    你的继承毫无意义。建筑物不是矩形,矩形也不是点。这是一项组合工作,而不是继承,您通过传递点等正确地做到了这一点 - 只需不要继承。

    除此之外,我不确定您的问题是什么。除了您已经在做的迭代之外,没有其他方法可以查询属性,除非您将其存储在某种数据结构中,该数据结构为您要查询的属性编制索引。

    【讨论】:

    • 丹尼尔,谢谢你帮助我。我因为没有意识到这不是继承问题而感到愚蠢。我想数据结构类似于 Django 中的多对一关系。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 2014-08-04
    • 1970-01-01
    相关资源
    最近更新 更多