首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么multiprocess.Process不能调用getattr方法?

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

Stack Overflow用户
提问于 2017-12-19 15:11:19
回答 1查看 171关注 0票数 0

尝试通过multiprocessing.Process中的getattr()调用say_hellosay_world两个方法,但尚未执行say_world方法。我怎么才能让它成为可能呢?谢谢。

代码语言:javascript
复制
# -*- 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()
EN

回答 1

Stack Overflow用户

发布于 2017-12-19 15:40:01

参数target需要一个对函数的引用作为值,但您的代码将None传递给它。以下是需要更改的部分:

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47881694

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档