如何 "address" 一个 Python 数据类实例?
How to "address" a Python dataclass instance?
我有一个 Python 数据类定义如下:
@dataclass(order=True)
class Accident:
name: str
year: int
month: int
num_accidents: int
我正在创建 'Accident' 个实例的列表,如下所示:
accidents_list = []
# For the year 2020, create instances to record accidents per month
for month in range(1,13):
# name will be in the format 2020-1, or 2020-2 and so on
name = "2020" + "-" + str(month)
# I am adding name, year and month, accidents to be added later
accidents_list.append(Accident(name, 2020, month))
我想加上事故的数量说2020-02,也就是2月份。
如何引用实例以添加事故数量?我不能在 for 循环中添加意外事件,因为我在创建此实例时没有数据。
我想做类似 2020-02.num_accidents = 5
的事情。我不想遍历 accidents_list,每个月都有一个 if 语句,如果列表真的很大,那将是太多的事情了。
for accidents in accidents_list:
if (accident.name == '2020-02'):
accident.num_accidents = 5
elif (accident.name = '2020-03'):
accident.num_accidents = 12
所以,是的,您确实需要遍历列表以使用 num_accidents
:
填充所有 Accident
实例
for accident in accidents_list:
year_month = f'{accident.year}-{accident.month}'
value = api.get_accidents_from_month(year_month)
if value:
accident.num_accidents = value
我有一个 Python 数据类定义如下:
@dataclass(order=True)
class Accident:
name: str
year: int
month: int
num_accidents: int
我正在创建 'Accident' 个实例的列表,如下所示:
accidents_list = []
# For the year 2020, create instances to record accidents per month
for month in range(1,13):
# name will be in the format 2020-1, or 2020-2 and so on
name = "2020" + "-" + str(month)
# I am adding name, year and month, accidents to be added later
accidents_list.append(Accident(name, 2020, month))
我想加上事故的数量说2020-02,也就是2月份。 如何引用实例以添加事故数量?我不能在 for 循环中添加意外事件,因为我在创建此实例时没有数据。
我想做类似 2020-02.num_accidents = 5
的事情。我不想遍历 accidents_list,每个月都有一个 if 语句,如果列表真的很大,那将是太多的事情了。
for accidents in accidents_list:
if (accident.name == '2020-02'):
accident.num_accidents = 5
elif (accident.name = '2020-03'):
accident.num_accidents = 12
所以,是的,您确实需要遍历列表以使用 num_accidents
:
Accident
实例
for accident in accidents_list:
year_month = f'{accident.year}-{accident.month}'
value = api.get_accidents_from_month(year_month)
if value:
accident.num_accidents = value