如何在Python中遍历数据类?

时间:2019-10-23 18:44:17

标签: python variables python-dataclasses

我想遍历python中的数据类,以找到符合特定条件的所有汽车,但是,该代码永远行不通,因为该变量被解释为属性,而不是变量。

from dataclasses import dataclass

@dataclass
class cars:
    year: int = 0
    model: str = "unknown"
    PS: int = 0
    colour: str = "unknown"

car_1 = cars(year = 1980, colour = "brown")
car_2 = cars(year = 1999, colour = "black", PS = 82)

owned_cars = [car_1, car_2]

criteria = input("Which criteria to search for? year, model, PS, colour")

for car in owned_cars:
    value = car.criteria
    print(value, car)
AttributeError: 'cars' object has no attribute 'criteria'

使用时:

value = car.year

代码运行正常。我该如何告诉python,它应该将标准解释为变量,并使用其内容而不是其名称?

1 个答案:

答案 0 :(得分:2)

这与car作为数据类无关。这就是Python属性的工作方式。如果要按名称在字符串中查找属性,请使用getattr

value = getattr(car, criteria)