如何抽象调用这个具体线程 类 的方式?

How to Abstract the way this concrete Thread classes are called?

我正在制作具体的 classes,它们是 Thread class 的子class,所以实际上它们是线程。 Class AB 在我的例子中。

我的 class Foo 得到一个 settings 字典,并得到一个 accounts 的列表(也是字典项)。然后我为每个帐户创建一个线程 A,它接受两个参数,整个设置字典和对应于每个帐户的帐户列表索引。

但是这个例子不能用classB。因为对我的 Thread Class A 的调用是硬编码的。我如何抽象 Foo class 以按需(动态地)使用 class 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

我真的不知道你想要达到什么目的,这是你想要的吗?

thread_class = {'A': A, 'B': B}
post_thread = thread_class['B'](self.settings, self.accounts[i])

但这也可以称为"hardcoded"...