Home > Software engineering >  Add attributes to class from list
Add attributes to class from list

Time:11-04

I have a list in a .txt file that includes data about cars. The list is like this:

Audi;2002;2500  
Peugeot;1967;2040  
Mercedes;2020;12000  

etc., there is 10 items in total.

I need to somehow use a class with brand, model and price as the attributes and make a list out of these. So a list of 10 elements with Audi 2002 2500 as the first line, Peugeot 1967 2040 as second line, etc.

I have gotten this far:

file = open("doc.txt", "r")

class CAR():
   brand = ""
   model = 0
   price = 0      

def readdoc(file, listA)
   lines = 0
   for line in file:
     lines = lines   1
     listA.append(line.strip())

This function gives me the file in a list format ['Audi;2002;2500, '...'].

But then I get lost on what to do. I am supposed to "combine" the list and the class CAR somehow to make a list where the first line is Audi 2002 2500 and then I would need to do some simple calculations with the price and model (for example multiplication).

CodePudding user response:

For each line you may split on ; and build the CAR instance with the 3 values

class CAR:
    brand: str
    year: int
    price: int

    def __init__(self, brand, year, price):
        self.brand = brand
        self.year = year
        self.price = price


def readdoc(file):
    result = []
    with open(file, "r") as file:
        for line in file:
            br, ye, pr = line.strip().split(";")
            result.append(CAR(br, int(ye), int(pr)))
    return result


cars = readdoc("doc.txt")

CodePudding user response:

As mentioned by @Bharel you can also assign instance attributes without the __init__ method, not how it is usually done (AFAIK), but basically it is the same thing:

class Car:
    brand: str = ''
    year: int = 0
    price: int = 0


def readfile(file):
    result = []
    with open(file, "r") as file:
        for line in file:
            brand, year, price = line.strip().split(";")
            car = Car()
            car.brand = brand
            car.year = year
            car.price = price
            result.append(car)
    return result


cars = readfile("doc.txt")
  • Related