Python中嵌套类的替代方案是什么

2 投票
1 回答
694 浏览
提问于 2025-04-16 21:38

我看到一篇帖子说“嵌套类不是很符合Python的风格”,那有什么替代的方法呢?

请原谅我,这个例子可能不是最好的,但它传达了基本概念。这里有一个嵌套类用来执行某个任务。我基本上需要在多个线程中连接到一个服务。

import threading, imporedlib

class Mother(threading.Thread):
    def __init__(self,val1,val2):
        self.VAL1 = val1
        self.VAL2 = val2
    def connectandrun():
        for i in range(5):
            Child.run(i)
    class Child:
        def run(self):
            importedlib.runajob(Mother.VAL1, Mother.VAL2)

1 个回答

7

你想要使用组合的方式:

import threading, importedlib

class Child:
    def __init__(self, parent):
        self.parent=parent

    def run(self):
        importedlib.runajob(parent.VAL1, parent.VAL2)



class Mother(threading.Thread):
    def __init__(self,val1,val2):
        self.VAL1 = val1
        self.VAL2 = val2

    def connectandrun():
        c= Child(self)
        for i in range(5):
            c.run(i)

当然,“母亲”和“孩子”这两个名字在这里其实不太合适,但你明白我的意思。

撰写回答