为什么不能multiprocess.Process调用getattr方法?

时间:2017-12-19 07:11:19

标签: python multiprocessing getattr

尝试在say_hello中按say_world调用两个方法getattr()multiprocessing.Process,但方法say_world尚未执行。我怎样才能成功呢?感谢。

# -*- coding: utf-8 -*-
from multiprocessing import Process
import time

class Hello:
    def say_hello(self):
        print('Hello')

    def say_world(self):
        print('World')


class MultiprocessingTest:
    def say_process(self, say_type):
        h = Hello()
        while True:
            if hasattr(h, say_type):
                    result = getattr(h, say_type)()
                    print(result)
            time.sleep(1)

    def report(self):
        Process(target=self.say_process('say_hello')).start()
        Process(target=self.say_process('say_world')).start() # This line hasn't been executed.


if __name__ == '__main__':
    t = MultiprocessingTest()
    t.report()

1 个答案:

答案 0 :(得分:1)

参数target需要将函数引用为值,但代码会将None传递给它。这些是改变的必要部分:

class Hello:
    def say_hello(self):
        while True:
            print('Hello')
            time.sleep(1)

    def say_world(self):
        while True:
            print('World')
            time.sleep(1)

class MultiprocessingTest:
    def say_process(self, say_type):
        h = Hello()
        if hasattr(h, say_type):
            return getattr(h, say_type) # Return function reference instead of execute function
        else:
            return None