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?
When instantiating an Area
pass it a reference to province
like:
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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments