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

2024-09-28 01:23:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个类的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)

这显然很难看,但目前确实管用。不过,我当然更希望不必先写出每个实例,然后再写出每个调用。我更喜欢在这两种情况下运行循环。你知道吗

当然,我可以使用list,但是当我尝试使用它时,它不起作用,因为我不能用\u args()遍历函数fn\u中的对象列表。*但是,可以遍历args。因此,我现在的问题是“如何将*args传递到run\u loop()调用中,以便只调用一次?”你知道吗

或者,如果有一种方法可以迭代对象列表,我想这也是一种选择,但是我不想这样做,因为它需要更多的代码行和相当一点的重构。你知道吗

感谢所有的意见,如果我需要解释的话请告诉我

谢谢

PS:我也意识到我可以简单地将对象的元素传递到一个列表中,但这会给程序带来不同的问题,而且似乎与oop结构背道而驰。你知道吗

编辑--->; 示例:

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

Tags: 实例runselfloopdefargsfnarg1
1条回答
网友
1楼 · 发布于 2024-09-28 01:23:02

使用潜在参数列表的一部分来做您想做的事情并不难:

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

不过,我建议您重新设计方法签名,只接受两个参数,一个对象和一个序列。您展示的代码一遍又一遍地打包和解压参数,如果您不需要的话,这有点浪费。只要去掉所有函数定义及其调用中的*,就可以得到更简单、更高效的代码。你知道吗

相关问题 更多 >

    热门问题