简体   繁体   中英

Multiple inheritance of class and threading in Python

I have an annoying problem in Python concerning the heritage of class. 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.

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. Here I tried to modify your code, in which I removed the inheritance between Fils and Mains and moved var inside 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM