Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing class instance through lists

I have two classes. Province creates a bunch of instances of Areas, and puts them in its self.areas list. I want for an Areas instance to access the attributes (or other data) of the Province instance which contains it in its self.areas list. To visualize:

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

How do I accomplish this? More importantly, is this even a correct approach? Is there a more reasonable and easier way to do this that I don't know of?

like image 760
Holsterbau Avatar asked Dec 18 '25 09:12

Holsterbau


1 Answers

When instantiating an Area pass it a reference to province like:

Code:

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)

Test Code:

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

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

Results:

area1 - This is stuff 
area2 - This is stuff 
like image 154
Stephen Rauch Avatar answered Dec 20 '25 23:12

Stephen Rauch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!