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 回答