生成单独的实例;将实例列表作为* args传递

时间:2014-07-02 02:13:24

标签: python function class instance args

我创建了一个类的5个实例,需要使用来自实例的参数调用另一个类,如:

class Class2:
    ...

    def __init__(self, arg1, arg2):
        self.time = 0
        ...

    def run_loop(self, arg, *args):
        ...

        while True:
            fn_with_args(*args)
            ...

            if self.time == 35:
                fn_print_exit()
                break

    def fn_with_args(self, *args):
        for i in args:
            if i != "none":
                fn_other()


clas1_ob1  = Clas1(arg1, arg2)
clas1_ob2  = Clas1(arg1, arg2)
clas1_ob3  = Clas1(arg1, arg2)
clas1_ob4  = Clas1(arg1, arg2)
clas1_ob5  = Clas1(arg1, arg2)

clas2_ob1  = Clas2(arg)

clas2_ob1.run_loop(clas1_ob1, "none")
clas2_ob1.run_loop(clas1_ob2, clas1_ob1)
clas2_ob1.run_loop(clas1_ob3, clas1_ob1, clas1_ob2)
clas2_ob1.run_loop(clas1_ob4, clas1_ob1, clas1_ob2, clas1_ob3)
clas2_ob1.run_loop(clas1_ob5, clas1_ob1, clas1_ob2, clas1_ob3, clas1_ob4)

它显然非常难看,但它现在确实有效。但是,我当然希望不必写出每个实例然后写出每个调用。我更愿意在两种情况下都运行循环。

我当然可以使用列表,但是当我尝试它时不起作用,因为我无法遍历函数fn_with_args()中的对象列表。 * args但是,可以迭代。所以我现在的问题是“如何将* args传递给run_loop()调用,这样我就可以简单地调用一次?”

或者,如果有一种方法可以迭代对象列表,我认为这也是一个选项,但我宁愿不这样做,因为它需要更多的代码行和相当多的重构。 / p>

感谢任何和所有的输入,如果我需要更多解释,请告诉我,

由于

PS:我也意识到我可以简单地将对象的元素传递给列表,但这会给程序带来不同的问题,并且似乎与oop结构相反。

EDIT ---> 例如:

number = 5
clas2_ob1  = Clas2(arg)
for i in range(number):
    clas1_ob1 = Clas1(arg1, arg2)
    clas2_ob1.run_loop(clas1_ob1, "none")
#This is the structure I want but this will obviously just overwrite 5 times
#The arguments in this case also become incorrect

1 个答案:

答案 0 :(得分:1)

使用一系列潜在参数来做你想做的事情并不难:

class1_objs = [Clas1(arg1, arg2) for _ in range(5)]    # create Class1 objects in a list
class2_obj  = Clas2(arg)

for i, obj in enumerate(class1_objs):     # loop over objects and indexes with enumerate
    class2_obj.runloop(obj, *class1_objs[:i] or ["none"])  # use index to slice the list

我建议您可能需要重新设计方法签名,只需接受两个参数,一个对象和一个序列。您展示的代码会一遍又一遍地打包和解包,如果您不需要它,这有点浪费。只需删除所有函数定义及其调用中的*,您就可以获得更简单,更高效的代码。