类的Python数据结构随年份而变化

时间:2019-01-28 08:33:44

标签: python python-3.x

我有一个这样的课程...

class person:
    def __init__(self, name):
        self.name = name
        self.carData = ""        
        self.HouseData = ""
        #other assets 

正在加载这样的数据...

for someone in person:
     someone.carData = runCarQuery()
     someone.HouseData = runHouseQuery()
     #load other assets

但是数据随年份而变化,例如2019、2020等,我正在努力以可视化的方式在数据结构中表示这种情况。我知道理论上我可以做到这一点...

class person:
    def __init__(self, name):
        self.name = name
        self.carData2019 = ""        
        self.HouseData2019 = ""
        self.carData2020 = ""        
        self.HouseData2020 = ""
        #other assets 

但是感觉非常笨拙,所以我希望有一种方法可以指向2019版本的carData对象。例如,一个数据模型支持类似...

for someone in person:
     someone.carData['2019'] = runCarQuery('2019')
     someone.carData['2020'] = runCarQuery('2020')
     someone.HouseData['2019'] = runHouseQuery('2019')
     someone.HouseData['2020'] = runHouseQuery('2020')
     #load other assets

我知道这是无效的,但是对于如何在python中实现场景有些迷失。

3 个答案:

答案 0 :(得分:2)

您的意思是:

# __init__
…
someone.carData = {}
someone.HouseData = {}

然后:

for someone in person:
    for year in (2019, 2020):
        someone.carData[year] = runCarQuery(year)
        someone.HouseData[year] = runHouseQuery(year)

答案 1 :(得分:1)

您可以使用@property https://docs.python.org/3/library/functions.html#property

class person:
    def __init__(self, name):
        self.name = name  
        self.HouseData = ""
        #other assets
    @property
    def carData(self):
        this_year = get_this_year()
        return  runCarQuery(this_year)

some_person = Person()

some_person.carData

答案 2 :(得分:1)

您可以创建一种为您执行过滤的方法:

class Person:
  def __init__(self, name):
      self.name = name
      self.car_data = []
      self.house_data = []

   def car_by_year(self, year):
      return filter(lambda x: x['date'].year() == year, self.car_data)

   def house_by_year(self, year):
      return filter(lambda x: x['date'].year() == year, self.house_data)

您必须在car_datahouse_data对象中获得一些数据结构,也许是一个存储年或日期值的字典。

p = Person('John')
p.car_data.append({'date': date(2018, 01, 01), 'model': 'Ford'})

for car in p.car_by_year(2018):
    print(car)