我正在创建从Thread类继承的具体类,因此实际上它们是线程。在我的示例中,类AB

我的班级Foo获取一个settings字典,并获取一个accounts列表(也包含字典项)。然后为每个帐户创建一个线程A,该线程带有两个参数,即整个设置字典和与每个帐户相对应的帐户列表索引。

但是此示例不能使用类B。因为对我的线程类A的调用是硬编码的。我如何抽象Foo类以按需(动态)使用类AB?好像他们是pluggable actions ...

我是线程和python的新手。我会接受任何其他存档相同行为的方式。或者,如果有更好的方法,请告诉我。

class Foo(object):

    def __init__(self, settings):
        self.settings = settings
        self.accounts = [
            {
                'username': 'DummyUser',
                'password': 'FIXME',
            },
            #...
        ]

    def start_threads(self):
        threads = []
        for i in range(len(self.accounts)):
            post_thread = A(self.settings, self.accounts[i])
            post_thread.setName(self.accounts[i]['username'])
            threads.append(post_thread)

        for t in threads:
            t.start() # Start running the threads!
            t.join()  # Wait for the threads to finish...

class A(Thread):

    def __init__(self, settings, account):
        Thread.__init__(self)
        self.settings = settings
        self.account = account

    def run(self):
        # Stuff...
        print('%s sleeping for %d seconds...' % (self.getName(), 60))
        time.sleep(60)

class B(Thread):

    def __init__(self, settings, account):
        Thread.__init__(self)
        self.settings = settings
        self.account = account

    def run(self):
        # Stuff...
        print('%s sleeping for %d seconds...' % (self.getName(), 60))
        time.sleep(60)

if __name__ == '__main__':
    settings = {
        'setting1': 'value1',
        'setting2': 'value2',
        #...
    }

    Foo(settings).start_threads()

最佳答案

class Foo:
    def __init__(self, settings, pluggable_action):
       ...
       self.pluggable_action = pluggable_action
    def start_threads(self):
       ....
       post_thread = self.pluggable_action(...)
       ...

 foo = Foo(settings, A) # or B

关于python - 如何抽象此具体Thread类的调用方式?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28526134/

10-12 22:51