Hello,
I'm trying to teach myself OOP to do a data project involving
hierarchical data structures.
I've come up with an analogy for testing involving objects for
continents, countries, and states where each object contains some
attributes one of which is a list of objects. E.g. a country will
contain an attribute population and another countries which is a list
of country objects. Anyways, here is what I came up with at first:
class continent(objec t):
def __init__(self,c ontinent_name):
self.name = continent_name
self.countries = []
def addCountry(self ,country_name):
self.countries. append(country_ name)
def listCountries(s elf):
for country in self.countries:
print country.name, "pop:",country. population,", states:"
country.listSta tes()
class country(object) :
def __init__(self,n ame):
self.name = name
self.population = 0
self.states = []
def addState(self,s tate_name):
self.states.app end(state_name)
def listStates(self ):
for state in self.states:
print " ",state.name,"p op:",state.popu lation
state.stateInfo ()
class state(object):
def __init__(self,s tate_name):
self.name = state_name
self.color = 'unknown'
self.counties = []
self.population = 0
def addCounty(self, county):
self.counties.a ppend(county)
def stateInfo(self) :
print " color:",self.co lor
print " counties",self. counties[:]
NAm = continent('NAm' )
usa= country('usa')
canada = country('canada ')
mexico = country('mexico ')
florida = state('florida' )
maine = state('maine')
california = state('californ ia')
quebec = state('quebec')
NAm.addCountry( usa)
NAm.addCountry( canada)
NAm.addCountry( mexico)
usa.addState(ma ine)
usa.addState(ca lifornia)
usa.addState(fl orida)
canada.addState (quebec)
florida.addCoun ty('dade')
florida.addCoun ty('broward')
maine.addCounty ('hancock')
california.addC ounty('marin')
florida.populat ion = 1000
california.popu lation = 2000
maine.populatio n = 500
quebec.populati on = 1000
florida.color = maine.color = california.colo r = 'blue'
NAm.listCountri es()
--------------------------------------------------------------------------
so this works but is far more cumbersome than it should be.
I would like to create an object when I add it
so I wouldn't have to do:
usa= country('usa')
NAm.addCountry( usa)
I could just do
NAm.addCountry( 'usa')
which would first create a country object then add it to a countries
list
to do this I tried:
def addCountry(self ,country_name):
# create an instance of country
exec(country_na me + "= country('" + country_name + "')")
# Add this new instance of a country to a list
exec("self.coun tries.append(" + country_name + ")")
Which doesn't give an error, but doesn't seem to create an instance of
the country object.
Does this make sense? Can this be done?
For my real project, I won't know the names and quantities of objects.
They will be highly variable and based on data contained in the
"parent" object.
Thanks