我是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)
1条答案
按热度按时间q3qa4bjr1#
您可以尝试将
fields
从类上的属性名到引用名设置为dict
。这样你就可以把所有的东西都放在一个地方。这将打印:
现在,您只需要在
fields
类变量中指定字段及其对应的reference
值。