连接函数名称和运行函数

时间:2019-05-18 09:44:38

标签: python for-loop

我有一个名为MyCar()的小类

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

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

然后我创建了该类的4个对象。

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

工作正常。当我为第一类运行函数时,它给了我所需的输出:

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

我想使用for循环并为我创建的类的每个实例运行该函数。

4 个答案:

答案 0 :(得分:1)

您可以创建汽车列表:

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

答案 1 :(得分:1)

只需创建一个参数列表,并从中创建一个类实例列表 。然后您可以使用该列表来调用函数

#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()

输出为

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

答案 2 :(得分:0)

只需创建汽车名称列表,然后在课程后添加以下代码即可:

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

输出:

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

答案 3 :(得分:0)

您还可以使用字典将var_name存储到值映射,并在需要时调用该类:

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)