I have a City object that has some attributes, including a list of houses:
city1 = {
'name': "Tokio",
'houses': [
{
'code': 1,
'residents': 4
},
{
'code': 2,
'residents': 2
}
]
}
My problem is that, within each object in the list of houses I need to have a method mount_description(self)
that needs to access the name
attribute of the external object City where this list of houses is inside:
class House():
code = None
residents = 0
def mount_description(self):
# get 'name' attribute of the external object
class City():
name = None
houses = list()
I know the correct thing would be for the City object to send the name
to the items in the list of houses, but unfortunately due to many details I cannot do this. I really need each Home object to be able to access the external object where it is located.
Does anyone know how to do this? Or if this is possible?
Give to the house a reference to its host city
class House():
code = None
residents = 0
city = None
def __init__(self, city, code, residents):
self.city = city
self.code = code
self.residents = residents
#Do what you want here
def mount_description(self):
print(self.city.name)
class City():
name = None
houses = list()
def __init__(self, json):
for house in json['houses']:
self.houses.append(House(self, house['code'], house['residents']))
self.name = json['name']
def set_name(self, newname):
self.name = newname
def print_name(self):
print(self.name)
Then you can do
city1_json = {
'name': "Tokio",
'houses': [
{
'code': 1,
'residents': 4
},
{
'code': 2,
'residents': 2
}
]
}
city = City(city1_json)
city.print_name()
house1 = city.houses[0]
house1.mount_description()
>>> Tokio
>>> Tokio
city.set_name("Paris")
city.print_name()
house1.mount_description()
>>> Paris
>>> Paris
I think you should need to build something like a most simple tree. For City, you have a list for houses, or children. Each house doesn't know where is located, so need a parent for the house, or city.
class House():
def __init__(self, code=None, residents=0):
self.code = code
self.residents = residents
self.parent = None
@property
def city(self):
# get 'name' attribute of the external object
if self.parent:
return self.parent.name
else:
return None
class City():
def __init__(self, name):
self.name = name
self.houses = list()
def add_house(self, house):
self.houses.append(house)
house.parent = self
def add_houses(self, houses):
self.houses += houses
for house in houses:
house.parent = self
city_1 = City('Tokyo')
house_1 = House(code=1, residents=4)
house_2 = House(code=2, residents=2)
city_1.add_house(house_1)
city_1.add_house(house_2)
city_2 = City('Chicago')
house_3 = House(code=1, residents=3)
house_4 = House(code=2, residents=5)
city_2.add_houses([house_3, house_4])
>>> house_1.city, house_3.city
('Tokyo', 'Chicago')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.