首页 > 解决方案 > Is it possible to refer to an attribute of an object though multiple layers in Python?

问题描述

Say I have these classes

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]

Am I able to refer to the house_number of any house in the city when I have an object of type City? If yes, how would I be able to do that?

标签: pythonobjectoop

解决方案


Firstly, these two lines probably don't mean what you think they mean:

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

In Python, [House] does not mean "a list of House objects". It means "a list containing one element, which is the House class". Python does not enforce type constraints on lists, but you can add type hints like this:

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

Note that this will not prevent you from doing self.houses.append("a string"), but a good IDE like PyCharm will display a warning. I also changed your variable name to something more intuitive (houses is a good name for a list of House objects).

Moving on to your actual question, suppose that we have the following classes:

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] = []

Now, given an instance of City, you can access all of the house numbers like this:

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)

Now you can place this code in a method on the City class, put the numbers in a list, or do anything you like.


推荐阅读