Home > database >  How to add class objects to the list? - Python
How to add class objects to the list? - Python

Time:10-07

I'm learning python here:

I have created this cars class below and I want to that result go to the list. What is the most efficiency way to do it?

class Car:
    def __init__(self, brand="", price=""):
        self.brand = brand
        self.price = price
        

    
    def __str__(self):

        return str(self.brand)   " "   str(self.price)

import random

      
carslist = ["Skoda", "Audi", "Volvo", "Ford", "VW", "BMW", "Opel" ]


car1 = Car()
car1.brand =  (random.choice(carslist))
car1.price = (random.randint(1000, 10000))

car2 = Car()
car2.brand = (random.choice(carslist))
car2.price = (random.randint(1000, 10000))


car3 = Car()
car3.brand = (random.choice(carslist))
car3.price = (random.randint(1000, 10000))


car4 = Car()
car4.brand = (random.choice(carslist))
car4.price = (random.randint(1000, 10000))


car5 = Car()
car5.brand = (random.choice(carslist))
car5.price = (random.randint(1000, 10000))

print(car1)

I did try it like this cars1 = car1details cars2 = car2details and list [car1details, car2details] but that's not probably the best way to do it.

Thanks for you help!

CodePudding user response:

here is an example of how to append objects to a list by using range()

When you append the Car object you can add variables

class Car(object):
    def __init__(self, number):
        self.number = number

my_objects = []

for i in range(100):
    my_objects.append(Car(i))

CodePudding user response:

The below seems to work nice (__repr__ was added since when we print the cars it is used)

import random

class Car:
    def __init__(self, brand="", price=0):
        self.brand = brand
        self.price = price
    def __str__(self):
        return str(self.brand)   " "   str(self.price)
    def __repr__(self):
        return str(self.brand)   " "   str(self.price)


cars_models = ["Skoda", "Audi", "Volvo", "Ford", "VW", "BMW", "Opel" ]
cars = [Car(random.choice(cars_models),random.randint(1000, 10000)) for _ in range(1,8)]
print(cars)

output

[BMW 2008, Volvo 3810, Skoda 8545, Skoda 6715, Ford 9792, Audi 6013, VW 1475]

CodePudding user response:

from random import randint

class Car():
    def __init__(self, name):
        self.name= name
        self.price = randint(1000, 10000)

    def __str__(self):
        return f'Car( Name: {self.name} | price {self.price})'

    def __repr__(self):
        return f'Car( Name: {self.name} | price {self.price})'




carsname = ["Skoda", "Audi", "Volvo", "Ford", "VW", "BMW", "Opel" ]
cars = []
for name in carsname:
  cars.append(Car(name))

Use a basic for :)

  • Related