0

这里要描述一个复杂的问题:

我想要一个函数 AB(),它通过一个中间值将一个输入映射到另一个输入。更具体地说,该函数由两个函数组成,我们调用 A() 和 B(),它们都返回字典(即 A[B[input]] --> result)

这是我当前文件目录的示例:

packageX/

    __init__.py
    get_part_of_B_expensively.py
    something_that_will_use_convert.py
    convert.py
    packageA/

        __init__.py
        get_the_entirety_of_A_expensively.py

在我的 convert.py 中,我有以下内容:

import get_part_of_B_expensively
from packageA import get_the_entirety_of_A_expensively
dict_A = packageA.get_the_entirety_of_A_expensively()

def get_B():

    result = {}
    result = get_part_of_B_expensively() # this is a very expensive operation
    result += get_rest_of_B_inexpensively() # shorthand for adding two dictionaries
    return result # returns a dictionary

dict_B = get_B() # hence why i call it once outside, and not inside AB()

def AB(input):
    return dictA[dictB[input]]

不要认为这是正确的,因为我无法在定义 get_B() 之前初始化 dict_B,并且我希望 AB() 的唯一参数是input,因为我想抽象它的实现。但是,我在全局范围内引入了一些变量,主要是 dict_B 和 dictA,我不确定这是否是最好的方法。我可以将 get_B() 分离到它自己的包中,但我仍然会在全局框架中的某个地方调用它们。不知道这应该是什么方法,我想尽可能少地调用 A() 和 B(),它们调用同一个包中的文件),但抽象函数 AB()。

4

1 回答 1

3

如果这就是你的模块所做的全部,我不会说保持这种状态有那么糟糕。对于仅处理特定数据的小型脚本,有时使用全局是可以的,尤其是当您将其用作只读时。(当您需要对全局变量进行变异或重新绑定时,会出现很多令人困惑的问题。)有很多值得尊敬的库具有存储各种全局参数的全局变量,例如从配置文件加载的自定义选项等。

对于更重量级的情况,如果您的任务更复杂,您可以创建一个基本上执行此操作的类:

class Convert(object):
    def __init__(self):
        self.A = packageA.get_the_entirety_of_A_expensively()
        self.B = getB() # or put get_B's code in here
    def AB(self, input):
        return self.A[self.B[input]]

converter = Convert()
converter.AB('blah')

如果您只需要做一件事,这可能是矫枉过正,但如果您需要参数化操作(例如,如果您有多个可能需要操作的 A 和 B 字典),这是要走的路。

于 2012-06-28T04:59:06.813 回答