concatenate function name and run function

I have a small class called MyCar()

class MyCar():    
    def __init__(self, name):
        self.name = name

    def engine_start(self):
        print("my car's name is " + self.name)

Then I have created 4 objects of the class.

c1 = MyCar("corolla")
c2 = MyCar("civic")
c3 = MyCar("coroll")
c4 = MyCar("civi")

Works perfectly fine. When i run the function for the 1st class, it gives me the desired outout:

 c1.engine_start(): 'my car's name is corolla'

I want to use a for-loop and run the function for each of the instances i have created of the class.

4 answers

  • answered 2019-05-18 09:47 Relandom

    You can create a list of cars:

    cars = [c1, c2, c3, c4]
    for car in cars:
        car.engine_start()
    

  • answered 2019-05-18 09:48 Devesh Kumar Singh

    Just create a list of parameters, and create a list of class instances from them . Then you can use that list to call your functions

    #List of names
    names = ["corolla", "civic", "coroll", "civi"]
    
    #List of instances of class MyCar
    cars = [ MyCar(item) for item in names]
    
    #Iterate through the list and call the function
    for c in cars:
        c.engine_start()
    

    The output is

    my car's name is corolla
    my car's name is civic
    my car's name is coroll
    my car's name is civi
    

  • answered 2019-05-18 09:58 ALFAFA

    Just create a list for car's name, add this code after the class:

    car_names=['corolla','civic','coroll','civi']
    for i in range(len(car_names)):
        MyCar(car_names[i]).engine_start()
    

    Output:

    my car's name is corolla
    my car's name is civic
    my car's name is coroll
    my car's name is civi
    

  • answered 2019-05-18 10:06 prabhudotpy

    You can also use dictionary to store the var_name to value mapping and call the class whenever you require:

    def call_fun(input_dict):
        for car in input_dict: 
            return MyCar(input_dict[car])
    
    input_dict = {"c1":"corolla","c2":"civic","c3":"coroll","c4":"civi"}
    call_fun(input_dict)