Home > OS >  Add class attributes from list (Python)
Add class attributes from list (Python)

Time:11-03

I have a class with three attributes (name, year and price), and I have a list with this info in form name;year;price (10 items on the list with format like that). How can I get all the data from the list and add them to a class in a way where I could use these class objects(?) later? I put an example of the code I have so far below

class CAR:
   name = ""
   year = 0
   price = 0

listaA = [ford;2002;2500, audi;1978;5000 ,toyota;2020;12500]

etc 

I managed to get the list to print in separate lines, but i doubt it helps very much...

So I would need to add the data from listA to the class CAR in a way where I could use the name, model and price later, for example to multiply the model with the price (for example)

Sorry for a bit of a dumb question but I am very new to Python

CodePudding user response:

Assuming you meant a multi-line string that could be converted to a list of lines, here's one way to convert each line to a Car object using Python dataclasses:

from dataclasses import dataclass


@dataclass
class Car:
    name: str
    year: int
    price: int

    def __post_init__(self):
        # Convert string values to integers
        self.year = int(self.year)
        self.price = int(self.price)


stringA = """\
ford;2002;2500
audi;1978;5000
toyota;2020;12500\
"""

listA = stringA.split('\n')
# ['ford;2002;2500', 'audi;1978;5000', 'toyota;2020;12500']


cars = [Car(*line.split(';')) for line in listA]

print(cars)

Output:

 [Car(name='ford', year=2002, price=2500),
  Car(name='audi', year=1978, price=5000),
  Car(name='toyota', year=2020, price=12500)]

CodePudding user response:

You need to do the initialisation of your variables in the init function. This way you can create a CAR object by passing these 3 variables name, year and price. Here I also added the repr function to print a CAR object using the print() function.

To create cars from a list, you can simply fill up your list with tuples and use tuple unpacking *() to create a new CAR object.

class CAR:

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

    def __repr__(self):
        return "Name: {}\nYear: {}\nPrice: {}\n".format(self.name, self.year, self.price)


# create list of cars
listA = [('ford', 2002, 2500), ('audi', 1978, 5000), ('toyota', 2020, 12500)]

# create one CAR instance
new_car = CAR(*listA[0])
print(new_car)

# create multiple CAR instances
car_list = []
for car in listA:
    car_list.append(CAR(*car))

for car in car_list:
    print(car)

'''
Name: ford
Year: 2002
Price: 2500

Name: ford
Year: 2002
Price: 2500

Name: audi
Year: 1978
Price: 5000

Name: toyota
Year: 2020
Price: 12500
'''

CodePudding user response:

This would be the manual approach (I like the @dataclass, though), also assuming that the input is actually a list of strings and integers.

"""
cleaning the class definition a bit and introducing proper printing
"""
class Car( object ):

    def __init__( car ):
        car.name = ""
        car.year = 0
        car.price = 0

    def __repr__( car ):
        return(
            "----------\nbrand: {}\nyear : {}\nprice: {}\n".format(
            car.name,
            car.year,
            car.price
            )
        )

listaA = [
    "ford", 2002, 2500,
    "audi", 1978, 5000,
    "toyota", 2020, 12500
]

"""
here is the piece of code generating the list of class objects.
"""
carlist = list()
for tpl in zip( *[ iter( listaA ) ] * 3 ):
    a = Car()
    a.name, a.year, a.price = tpl
    carlist.append( a )


for car in carlist:
    print( car )

resulting in

----------
brand: ford
year : 2002
price: 2500

----------
brand: audi
year : 1978
price: 5000

----------
brand: toyota
year : 2020
price: 12500

  • Related