-2

I need something that let me use one variable in every class. I have multiclasses that I will use with threading.

class a():
    def __init__(self):
        self.run = True
    def aloop(self):
        while self.run:
            ###do  a things

class b():
    def __init__(self):
        self.run = True

    def bloop(self):
        while self.run:
            ###do b things

class c():
    def __init__(self):
        self.run = True

    def cloop(self):
        while self.run:
            ###do c thinks
    def close(self):
        self.run = False

Is it possible to connect all runs? So, when one is closed, others should also closed. I am trying to use this style for ending loops but it can be used for other purposes.

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

0

You can control it by a single global variable, but as I think you need to do something more than that, inheritance structure can be helpful to you.

class Parent_thread:
    run = False

    def make_true(self):
        print(f'{self} object called make_true')
        Parent_thread.run = True

    def make_false(self):
        print(f'{self} object called make_false')
        Parent_thread.run = False

    def get_run_status(self):
        return self.__class__.run

    # other common functionalities.


class A(Parent_thread):
    def __init__(self):
        self.make_true()


class B(Parent_thread):
    def __init__(self):
        self.make_true()


obj_A = A()
obj_B = B()

obj_A.make_false()
print(obj_B.get_run_status())

output:

<__main__.A object at 0x00000283B5E46A90> object called make_true
<__main__.B object at 0x00000283B5E46A30> object called make_true
<__main__.A object at 0x00000283B5E46A90> object called make_false
False
S.B
  • 13,077
  • 10
  • 22
  • 49
  • 1
    Thank you for help, this is kinda thing that I am trying to find. I like your aproach. Let me ask something, what if there is another parent class needed for class B or class A? – Hakan Ulusoy Jul 14 '21 at 13:07
  • I think I found the way about it: https://stackoverflow.com/questions/3277367/how-does-pythons-super-work-with-multiple-inheritance – Hakan Ulusoy Jul 14 '21 at 13:13
  • @HakanUlusoy Happy to help. You can have multiple inheritance, As long as this `Parent_thread` is in the `B.mro()` for example, `B` can have access to Parent_thread's `run` attribute. btw you can upvote the answers which you find them useful. – S.B Jul 14 '21 at 16:25