通过列表引用类实例

时间:2018-03-03 19:05:01

标签: python arrays python-3.x class oop

我有两节课。 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

我如何做到这一点?更重要的是,这甚至是一种正确的方法吗?是否有更合理,更简单的方法来做到这一点,我不知道?

1 个答案:

答案 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