【问题标题】:Is it possible to refer to an attribute of an object though multiple layers in Python?是否可以通过 Python 中的多个层来引用对象的属性?
【发布时间】:2021-06-17 15:22:39
【问题描述】:

假设我有这些课程

class House:
    def __init__(self, area: int, house_number: int):
        self.area = area
        self.house_number = house_number


class Neighborhood:
    def __init__(self):
        self.neighborhood = [House]


class City:
    def __init__(self):
        self.city = [Neighborhood]

当我有一个类型为 City 的对象时,我是否能够引用该城市中任何房子的 house_number? 如果是,我将如何做到这一点?

【问题讨论】:

    标签: python object oop


    【解决方案1】:

    首先,这两行可能并不像您认为的那样:

            self.neighborhood = [House]
    ...
            self.city = [Neighborhood]
    

    在 Python 中,[House] 并不意味着“房屋对象列表”。它的意思是“包含一个元素的列表,即House 类”。 Python 不对列表强制执行类型约束,但您可以像这样添加type hints

    from typing import List
    ...
            self.houses: List[House] = []
    

    请注意,这不会阻止您执行self.houses.append("a string"),但是像 PyCharm 这样的良好 IDE 会显示警告。我还将您的变量名称更改为更直观的名称(housesHouse 对象列表的好名称)。

    继续您的实际问题,假设我们有以下类:

    from typing import List
    
    
    class House:
        def __init__(self, area: int, house_number: int):
            self.area = area
            self.house_number = house_number
    
    
    class Neighborhood:
        def __init__(self):
            self.houses: List[House] = []
    
    
    class City:
        def __init__(self):
            self.neighborhoods: List[Neighborhood] = []
    

    现在,给定City 的实例,您可以像这样访问所有门牌号:

    chicago = City()
    lakeview = Neighborhood()
    chicago.neighborhoods.append(lakeview)
    lakeview.houses.append(House(2000, 5))
    lakeview.houses.append(House(3000, 17))
    
    for neighborhood in chicago.neighborhoods:
        for house in neighborhood.houses:
            print(house.house_number)
    

    现在您可以将此代码放入City 类的方法中,将数字放入列表中,或做任何您喜欢的事情。

    【讨论】:

    • 谢谢,帮了大忙!
    猜你喜欢
    • 2021-12-03
    • 2011-06-06
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-03
    • 2021-12-29
    相关资源
    最近更新 更多