1

I would like to loop through a dataclass in python, to find all cars, which fit a certain criteria, however, the code never works, because the variable gets interpreted as an attribute, and not a variable.

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'

When using:

value = car.year

the code runs fine. How can I tell python, it should interpret criteria as the variable and use its content, instead of its name?

Tasmotanizer
  • 337
  • 1
  • 5
  • 15

1 Answers1

2

This doesn't have anything to do with car being a dataclass. It's just how Python attributes work. If you want to look up an attribute by its name in a string, use getattr:

value = getattr(car, criteria)
Brown Bear
  • 19,655
  • 10
  • 58
  • 76
Blckknght
  • 100,903
  • 11
  • 120
  • 169
  • not an answer, and not a duplicate but great Q. – droid192 Apr 27 '20 at 14:02
  • 2
    @qrtLs: I'm not sure what you mean by that. This answers how to turn a string like `"year"` into an attribute lookup equivalent to `car.year`, which was what the questioner wanted (as judged by their choice to accept this answer). It may be that you have some other issue you should ask about separately. – Blckknght Apr 27 '20 at 22:11