我有两节课。 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
我如何做到这一点?更重要的是,这甚至是一种正确的方法吗?是否有更合理,更简单的方法来做到这一点,我不知道?
答案 0 :(得分:2)
实例化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