[英]Multiple inheritance of class and threading in Python
I have an annoying problem in Python concerning the heritage of class. 我在Python中有一个关于类继承的烦人的问题。 The code is the following: 代码如下:
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()
My problem is when I call "Main", I don't manage to print the self.var variable from Fils class. 我的问题是,当我调用“ Main”时,我无法从Fils类中打印出self.var变量。
Someone know why? 有人知道为什么吗? And how can I fix it? 我该如何解决?
I don't understand what you are trying to achieve but it seems you are trying to experiment with threads, The above implementation exceeds recursion depth because you have a cyclic dependency, __init__
from Main class depends on self.fils_on()
and it construct Fils()
which trigger Fils.__init__()
which in turn calls Main.__init__(self)
and again the whole process continues. 我不明白您要达到的目标,但似乎您正在尝试使用线程,上述实现超出了递归深度,因为您具有循环依赖性,Main类的__init__
依赖于self.fils_on()
并构造Fils()
触发Fils.__init__()
,而Fils.__init__()
依次调用Main.__init__(self)
,整个过程再次继续。 Here I tried to modify your code, in which I removed the inheritance between Fils and Mains and moved var inside Fils. 在这里,我尝试修改您的代码,其中删除了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.