[英]Multiple inheritance of class and threading in Python
我在Python中有一個關於類繼承的煩人的問題。 代碼如下:
import time
from threading import Thread
class Main:
def __init__(self):
self.var = 0
self.fils_on()
def fils_on(self):
self.temp = Fils()
self.temp.start()
def fils_off(self):
self.temp.stop()
del self.temp
class Fils(Thread, Main):
def __init__(self):
Main.__init__(self)
Thread.__init__(self)
self.encore = True
def run(self):
i = 0
while self.encore:
chaine = str(i)
print chaine
print "var: ", self.var
i += 1
time.sleep(1)
def stop(self):
self.encore = False
if __name__ == "__main__":
main = Main()
我的問題是,當我調用“ Main”時,我無法從Fils類中打印出self.var變量。
有人知道為什么嗎? 我該如何解決?
我不明白您要達到的目標,但似乎您正在嘗試使用線程,上述實現超出了遞歸深度,因為您具有循環依賴性,Main類的__init__
依賴於self.fils_on()
並構造Fils()
觸發Fils.__init__()
,而Fils.__init__()
依次調用Main.__init__(self)
,整個過程再次繼續。 在這里,我嘗試修改您的代碼,其中刪除了Fils和Mains之間的繼承關系,並將var移到了Fils中。
import time
from threading import Thread
class Main:
def __init__(self):
self.fils_on()
def fils_on(self):
self.temp = Fils()
self.temp.start()
def fils_off(self):
self.temp.stop()
del self.temp
class Fils(Thread):
def __init__(self):
Thread.__init__(self)
self.encore = True
self.var = 0
def run(self):
i = 0
while self.encore:
chaine = str(i)
print chaine
print "var: ", self.var
i += 1
time.sleep(1)
def stop(self):
self.encore = False
if __name__ == "__main__":
main = Main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.