5

同じクラスにいくつかの論理プロセスを実装しています。クラスインスタンスは、プロセスごとにジェネレーターを取得し、そのジェネレーターをrun()進めます。私の場合、ジェネレーターは終了しません。

以下のコードでfoo_functionfoo_objectをどのように呼び出しますか?

class C(threading.Thread):
    def foo_function(self):
        """ generator *function*,
            logical process foo """
        while True:
            # some state checks
            if self.some_attr:
                # side-effects here
                pass
            yield

    def __init__(self):
        # generator *object*
        # i.e. process instance
        self.foo_object = self.foo_function()  # <- here

    def run(self):
        while True:
            next(self.foo_object)
            next(self.another_object)
            if xxx:
                next(self.yet_another_object)

典型的なプロセスは、、、discoveryなどauthenticationですwatchdog

ジェネレーターとジェネレーター オブジェクトを含む属性を適切な方法で定義する関数に名前を付けるにはどうすればよいですか?

最後に、同じ名前の名前は非常識ですよね?

class C:
    def foo(self):
        yield 1; yield 2
    def __init__(self):
        self.foo = self.foo()

c = C()            
type(C.foo) is function
type(c.foo) is generator
4

3 に答える 3

3

ジェネレーターがメソッド内でのみアクセスされる場合は、次のrunようなことができます。

class C:
    def a_process(self):
        while True: yield

    def another_process(self):
        while True: yield

    def run(self):
        # Use itertools.izip in python 2
        for _ in zip(a_process(), another_process()):
            pass

ここではzip、 for ループがジェネレーターを自動的に作成して進めます。この方法では、それらを追跡する必要はありません。

メソッド外のジェネレーターにアクセスする必要がある場合は、ジェネレーターrunの順序付けられた辞書を作成できます (ジェネレーターを定義された順序で進める必要がある場合)。

from collections import OrderedDict

class C:
    # Processes here

    def __init__(self):
        self.generators = OrderedDict()
        for gn in ('a_process', 'another_process'):
            self.generators[gn] = getattr(self, gn)()

    def run(self):
        while True:
            for g in self.generators.values():
                next(g)
于 2014-11-18T15:58:50.963 に答える