[英]what's the alternative to nested classes in Python
我讀了一篇文章說“嵌套類不是pythonic”還有什么選擇
請原諒我,這不是最好的例子,但它是基本概念。 用於執行任務的嵌套 class。 我基本上必須在多個線程中連接到服務。
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)
當然,“母親”和“孩子”的名字在這里不再合適了,但你明白了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.