gpt4 book ai didi

python - 通过列表引用类实例

转载 作者:行者123 更新时间:2023-11-28 17:08:53 26 4
gpt4 key购买 nike

我有两个类(class)。 Province 创建了一堆 Areas 的实例,并将它们放在它的 self.areas 列表中。我想要一个 Areas 实例来访问 Province 实例的属性(或其他数据),该实例将它包含在其 self.areas 列表中。可视化:

class Province:
def __init__(self, stuff="spam"):
self.stuff = stuff
self.areas = list()
def makeareas(self):
# make instances of Areas and put them in self.areas

class Areas:
def __init__(self):
pass
def access_stuff(self):
# access stuff of the Province where it is in its list

我该如何实现?更重要的是,这是否是一种正确的方法?有没有我不知道的更合理、更简单的方法?

最佳答案

当实例化一个 Area 时,将一个对 province 的引用传递给它,例如:

代码:

class Province:
def __init__(self, stuff="spam"):
self.stuff = stuff
self.areas = list()

def makeareas(self, area):
self.areas.append(Areas(area, self))

class Areas:
def __init__(self, area, province):
self.area = area
self.province = province

def access_stuff(self):
# access stuff of the Province where it is in its list
return '%s - %s ' %(self.area, self.province.stuff)

测试代码:

p = Province('This is stuff')
# Examples
p.makeareas('area1')
p.makeareas('area2')

for area in p.areas:
print(area.access_stuff())

结果:

area1 - This is stuff 
area2 - This is stuff

关于python - 通过列表引用类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49088078/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com