我读到一篇文章说“嵌套类不是 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/