不完全清楚您打算如何更新国家/地区数据,但听起来您需要的只是将国家/地区数据对象存储在字典中,使用一系列类似数据库的函数进行查询,如下所示:
country_data = {}
def add_country_data(name, year, *args, **kwargs):
country = Country(name, *args, **kwargs)
if name in country_data:
country_data[name][year] = country
else:
country_data[name] = {year: country}
def get_latest_data(country_name):
years = country_data[country_name].keys()
return country_data[country_name][max(years)]
def get_max_country(attr, year=None):
""" Returns the county with the max value of the given attribute
in the given year or (if year is ommitted) any year """
r = None
highest = None
for name, country in country_data.items():
if year is None:
max_v = max(getattr(country[y], attr) for y in country.keys())
else:
max_v = getattr(country[year], attr)
if highest is None or max_v > highest:
highest = max_v
r = name
return r, highest
def get_latest_dicts():
return {name: get_latest_data(name).__dict__
for name in country_data.keys()}
add_country_data("Venezuela", 1989, 100, 20, 50)
add_country_data("Venezuela", 2009, 120, 30, 40)
add_country_data("Brazil", 2008, 110, 40, 90)
print get_latest_data("Venezuela").immigrants # 120
print get_max_country("infected") # ('Brazil', 40)
print get_latest_dicts() # ('Brazil': {'immigrants: 110 ...
如果需要,可以将这些函数和数据字典作为
class methods
class Country(object):
""" Modeling a country immigration. """
data = {}
def __init__(self, name, immigrants, population, disease_numbers):
self.name = name
self.immigrants = immigrants
self.infected = population
self.disease_numbers = disease_numbers
@classmethod
def add_data(cls, year, *args, **kwargs):
obj = cls(*args, **kwargs)
cls.data[obj.name, year] = obj
# ...
Country.add_data("Venezuela", 1989, 100, 20, 50)
这很方便,因为与国家数据存储和查询相关的所有功能都可以与您需要的任何建模方法一起存储在国家类中。