Information exchange between Python classes

1

How can I exchange information between two different classes? I need to move data from one to the other. Each class is running in a different process.

An example of the structure, the code is too large, so there goes an example, the only difference of the real code is what it has inside the classes. I need to report to funcao01 and funcao02 , for example.

class Aplicativo():

    def funcao01(self):
        print("teste 01")


class Aplicativo2():
    def funcao02(self):
        print("teste 02")

App = Aplicativo()
App2 = Aplicativo2()

def Telas():
    App.funcao01()

def Comunicacao():
    App2.funcao02()

p = Process(target=Telas)
p1 = Process(target=Comunicacao)



def main():

    p.start()
    p1.start()
    p.join()
    p1.join()



if __name__ == "__main__":
    main()
    
asked by anonymous 15.12.2017 / 19:20

1 answer

1

A major problem with the code above is that it is not using "classes" - it is doing the declaration of functions in the body of a class - the way it is, they are not "methods" , are even functions, which know nothing of the class within which they were declared. This ends up generating an artificial namespace, which works for those who will call these functions from the outside, but it is rather strange when these "functions within the class" have to call each other, or share an "attribute": they will have to prefix the class name extensively.

The most appropriate way to do this would be to create a __init__ method in classes, and put the class itself as the target of the processes - this way you will have a "zeroed" instance of each class in each process.

It may be interesting to read some documentation and to better understand how this works. This article seems to be a good start (I did not read it carefully, but it seems to have the basics) link

If you find it difficult to use classes and methods in ways that make sense, remember that Python does not force you to use them when your architecture does not need it: you can use simple functions. In the same code example, the Telas and Comunicacao functions themselves have no reason to call another function within the classes - they could execute the task directly.

After you sort this out: the way to communicate data between distinct processes is by using the Multiprossecing.Queue and Multiprocessing.Pipe classes - their use with a small example is documented here: link

Your code example is so minimal that you can not tell what you'd like to communicate from side to side so any example I created here would be equivalent to what's in the official Python documentation above.

    
16.12.2017 / 17:01