python - Python 中嵌套类的替代方法是什么

标签 python multithreading nested-class

我读到一篇文章说“嵌套类不是 pythonic”还有什么选择

请原谅我,这不是最好的例子,但这是基本概念。用于执行任务的嵌套类。我基本上必须在多个线程中连接到服务。

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)

最佳答案

你想使用组合:

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)

当然,“母亲”和“ child ”这两个名字在这里不再合适,但你明白了。

关于python - Python 中嵌套类的替代方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6712442/

相关文章:

c++ - C++中的嵌套类

c# - Log4net : Rolling File Operation : Failing with Source does not exist

c++ - 在嵌套类中对 operator[] 的调用不明确

Python:如何选取相邻元素?

python - 无法使用pysockets从服务器接收消息

用于基于时钟的仿真的 Java 多线程

android - 为什么在 Intent 重定向代码之后执行代码?

c++ - 嵌套类的静态对象可以在没有类定义的情况下声明

python - 在python中将2D数组插入3D数组

python - 独立运行python测试模块