简体   繁体   中英

Construct class in a thread Python

I have a class:

class Fee:
    def __init__(self):
        self.fie = foe()

    def foo(self):
        return bar

How can I create an instance of Fee but into a thread; run the constructor of Fee into a thread ?

I don't think that a thread should be used solely to return a class, but if you'd like to incorporate a class into a thread you could try something like:

import threading

class Fee:
    def __init__(self):
        self.fie = 42

    def print_fie(self):
        print(self.fie)


def build_thread():
    new_fee_instance = Fee()
    new_fee_instance.print_fie()


if __name__ == '__main__':
    my_thread = threading.Thread(target=build_thread)
    my_thread.start()
    my_thread.join()

Result:

42

Process finished with exit code 0

I'm not sure if this is the cleanest way to build a class in a thread, but I think my logic with them is typically to have a thread attached to a function -> that function builds a class and uses it. I'm not sure what motivations you have to create a thread solely to return a class and not do any processing with it, but I imagine the overhead to creating a thread for such a purpose would negatively impact your program's speed because there is overhead to creating threads and that could be avoided.

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