2

そのため、入力に基づいてオブジェクトの初期化時にメソッドを変更する必要があります__init__(関心のある人のために、navigate_toインスタンス化されている自動化ツールのタイプ (Selenium、モバイル デバイス自動化機能など) に基づいて、テスト フレームワークでメソッドを変更しています)。で条件付きで作成されたクロージャーを使用して解決策を考え出しましたが、__init__これを行うには、よりエレガントで最適化された方法が必要なようです。アプローチの例として:

class Foo(object):
    def __init__(self, x):
        self.x = x
        if x % 2:
            def odd_or_even():
                return '%d odd' % self.x
        else:
            def odd_or_even():
                return '%d even' % self.x
        self.odd_or_even = odd_or_even

その結果:

>>> foo1 = Foo(1)
>>> foo2 = Foo(2)
>>> foo1.odd_or_even()
'1 odd'
>>> foo2.odd_or_even()
'2 even'

これは機能しますが、これを行うためのより良い方法があるはずだと感じています。提案?

4

2 に答える 2

3

私はこれを委任することをお勧めします-のようなもの

class Automator(object):
    def navigate_to(self, url):
        pass

class SeleniumAutomator(Automator):
    def navigate_to(self, url):
        # do it the Selenium way
        pass

class MobileAutomator(Automator):
    def navigate_to(self, url):
        # do it the mobile-browser way
        pass

class Foo(object):
    def __init__(self, x, automator):
        self.x = x
        self.automator = automator

    def navigate_to(self, url):
        return self.automator.navigate_to(url)

f = Foo(3, SeleniumAutomator())
f.navigate_to('http://www.someplace.org/')

...これは関数だけで行うことができますが、インターフェイスに依存するメソッドがたくさんあると思います。それらをクラスにグループ化しておくのが最もクリーンなようです。

編集:ああ-それならあなたが欲しいのはFooではなく、オートマトンファクトリーです-のようなもの

def makeAutomator(type, *args, **kwargs):
    return {
        "selenium": SeleniumAutomator,
        "mobile":   MobileAutomator
    }[type](*args, **kwargs)

myauto = makeAutomator("selenium")
于 2012-05-29T22:06:47.437 に答える
1

自動化ツールのタイプごとに異なるメソッドを作成し、次に、の状態を使用しselfて特定のメソッドのどれを呼び出すかを決定するジェネリック メソッドを作成します。

に決定を記録するだけでよいのに、決定を含むクロージャを作成する必要があるのはなぜselfですか?

于 2012-05-29T22:11:15.797 に答える