0

我正在寻找一种更简洁的方法来编写lookup_and_url函数。我认为必须有一种更简洁的方式来声明和实现我的逻辑。我已尽力准确描述代码本身的外部函数和内部函数:

def render(opener='corp'):
    """render will render a carousel of videos, with the opener being
    corp or uk and the follower being the other"""

    def lookup_and_url():
        """"lookup_and_url() returns the DOM id and url for the
        opening video (the opener) and the video to follow (the follower).

        It returns a dictionary that allows a loop to make a DOM
        lookup of the id of the HTML element and then replace its
        `src attribute with the provided URL
        """

        src = dict(
            corp='http://www.youtube.com/embed/0lrqEGlu0Fo',
            uk='http://www.youtube.com/embed/30MfCTLhdZ4'
        )

        if opener == 'corp':
            return dict(
                opener = dict(lookup='opener', src=src['corp']),
                follower = dict(lookup='follower', src=src['uk'])
            )
        else:
            return dict(
                opener = dict(lookup='opener', src=src['uk']),
                follower = dict(lookup='follower', src=src['corp'])
            )

    lookup_and_src = lookup_and_url()

    for replace in lookup_and_src:
        root.findmeld(lookup_and_src['lookup']).attributes(src=lookup_and_src['src'])
4

2 回答 2

3

您的内部函数似乎唯一要做的就是选择两个 URL 中的哪个是“开启者”,哪个是“跟随者”。您为构建嵌套字典所做的所有工作都是毫无意义的。我认为您可以使这变得非常简单:

def render(opener='corp'):
    corp = 'http://www.youtube.com/embed/0lrqEGlu0Fo',
    uk = 'http://www.youtube.com/embed/30MfCTLhdZ4'

    o, f = (corp, uk) if opener == "corp" else (uk, corp)

    root.findmeld('opener').attributes(src=o)
    root.findmeld('follower').attributes(src=f)

我认为,如果没有所有字典,这更容易理解。

于 2013-09-02T16:39:26.130 回答
1

如果您将以下内容提取到另一个字典中(如果您有两个以上的条目),会不会更容易?

src = {
    'corp': 'http://www.youtube.com/embed/0lrqEGlu0Fo',
    'uk': 'http://www.youtube.com/embed/30MfCTLhdZ4',
}

followers = {
    'corp': 'uk', 
    'uk': 'corp',
}

return {
    'opener': {'lookup': 'opener', 'src': src[opener]},
    'follower': {'lookup': 'follower', 'src': src[followers[opener]]},
}
于 2013-09-02T16:40:41.837 回答