python-3.x 在类中维护一个可以导出为CSV行的大属性列表

nukf8bse  于 2023-10-21  发布在  Python
关注(0)|答案(1)|浏览(139)

我是Python新手,试图以CSV格式存储数据列表。
我有一个csv的 Package 器类,每一行都有一个DataRow。但是,我知道这段代码不是很容易维护。
目前,如果我想添加一个新值,我需要在set_item中添加一个条件,在fields中添加一个新字段,并在类中添加一个新属性。
有没有更好的解决方案来维护类中的属性列表?
理想情况下,我的DataRow类将只有一个fields列表,其中包含一些泛型方法。

class DataRow:
  
  # These are used as the column headings in the csv. 
  # They are just the accessible keys.
  fields: List[str] = ['id', 'name', 'created', 'time']

  # I still want to reference specific values so I add them to class
  # I have so many properties I don't really want to list them all here.
  id:str
  name:str
  created: str
  time: str
  
  def __init__(self) -> None:

  def get_labels(self) -> List[str]:
    return self.fields
  
  # reference is a string from external source so need to map it to a property
  def set_item(self, reference:str, value:str):
    # in this case reference doesn't match up with the property name
    if reference == 'my id':
      self.id = value
    if reference == 'item name':
      self.name = value
    if reference == 'date':
      self.created = value
    if reference == 'time':
      self.time = value
   
   def get_item(self, key:str):
      # I want to get the property based on field self[name]
    

class DataFile:
    name: str
    rows: List[DataRow] = []

    def __init__(self, name: str) -> None:
        self.name = name
    
    def open(self):
       # will open the csv file and set the rows

    def save(self):
       # will save the latest rows to csv file
    
    def add_row(id: str, row:DataRow ):
       self.rows.append(row)
q3qa4bjr

q3qa4bjr1#

您可以尝试将fields从类上的属性名到引用名设置为dict。这样你就可以把所有的东西都放在一个地方。

class DataRow:
    fields = {'id': 'my id', 'name': 'item name', 'created': 'date', 'time': 'time'}
    # _ref_to_field[reference] = field_name
    _ref_to_field = {v: k for k, v in fields.items()}
    # used to save some memory because __dict__ is not needed
    __slots__ = tuple(fields.keys())

    def get_labels(self) -> list[str]:
        return list(self.fields)
    
    def set_item(self, reference:str, value:str):
        setattr(self, self._ref_to_field[reference], value)
    
    def get_item(self, key:str):
        return getattr(self, key)

# testing the DataRow class
row = DataRow()
row.set_item('my id', '12345')
row.set_item('item name', 'foo bar')
row.set_item('date', '1970-01-01')
row.set_item('time', '00:00:00')
for field in row.get_labels():
    print(field, row.get_item(field))

这将打印:

id 12345
name foo bar
created 1970-01-01
time 00:00:00

现在,您只需要在fields类变量中指定字段及其对应的reference值。

相关问题