python - 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?
解决方案
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.
推荐阅读
- scala - Having only a JAR Maven Archetype file, how can it be generated a new project?
- python - Print/Warning for Null values with column name and count
- mysql - 列数与第 1 行的值数不匹配,但为什么呢?
- dart - json.decode 之后的空检查
- ios - ViewControllers、内存消耗和代码效率
- android - 传递类型数组时未加载图像
- amazon-web-services - 在 CloudFormation 模板中为“AWS::ApiGateway::Resource”指定 ParentId
- ios - 将数组与参考数组进行比较并删除重复项
- ios - 如果没有连接,为什么调用 swiftHTTP 响应处理程序?
- typo3 - TYPO3 felogin - 创建带有挂钩的自定义标记以根据语言呈现内容?