2015-02-17 57 views
2

我的問題很簡單:我只需要將一個字符串(一個路徑和一個文件名)傳遞給一個模塊,以供該模塊中的函數使用。換句話說,函數需要路徑(和文件名)才能工作,每次調用函數時傳遞該字符串都是不現實的。將字符串傳遞給模塊「一次」

有沒有一種方法可以實際傳遞一次字符串(也許可以在腳本中稍後更改),並將其保存在模塊中供以後使用?

+0

你可能只是有一些「init_module()」函數來設置模塊內的共享變量 – MightyPork 2015-02-17 20:53:47

回答

3

你可以簡單地設置一個全局模塊中:

variable_to_use = None 

def funcA(): 
    if variable_to_use is None: 
     raise ValueError('You need to set module.variable_to_use before using this function') 
    do_something_with(variable_to_use) 

variable_to_use是全球性的模塊中的所有代碼。然後,其他代碼可以這樣做:

import module_name 

module_name.variable_to_use = 'some value to be used' 

不要被誘惑然而使用from module_name import variable_to_use,因爲這將創建一個本地引用,而不是,然後是反彈,使模塊的全球不變。

您可以封裝設置,全球的功能:

def set_variable_to_use(value): 
    global variable_to_use 
    variable_to_use = value 

,並使用該函數,而不是直接設置模塊全球的。

+0

這正是我所做的!我使用全局路徑字符串並將其作爲參數傳遞給我的函數。 – 2015-02-17 20:55:42

+1

@MalikBrahimi:不,你沒有。您可以設置功能默認值。 *這不是一回事*。請參閱[「Python中的最小驚訝」:可變的默認參數](http://stackoverflow.com/q/1132941) – 2015-02-17 20:56:16

+0

@MalikBrahimi:測試你的代碼,你會發現*它不能像那樣工作*。當函數被定義時,'arg'默認值被設置**一次**,例如,當模塊被導入時。你不能改變'路徑',並期望這些默認值跟隨,因爲*他們不會再被設置*。 – 2015-02-17 20:56:35

2

一種選擇是將函數添加到類中,並使用對象實例來保存不同的可重用值。

class Foo(): 
    def __init__(self, fpath, fname): 
     self.fpath = fpath 
     self.fname = fname 

    def funcA(self): 
     print "do something with the path: {}".format(self.fpath) 

    def funcB(self): 
     print "do something with the filename: {}".format(self.fname) 

if __name__ == '__main__': 
    my_object = Foo("/some/path/", "some_filename") 
    my_object.funcA() 
    my_object.funcB() 
1

您可以添加一個設置功能到您的模塊,例如,

import functools 

_path = None 

def setup(path): 
    global _path 
    _path = path 

def setup_required(func): 
    @functools.wraps(func) 
    def wrapped(*args, **kwargs): 
     global _path 
     if _path is None: 
      raise RuntimeError('setup required') 
     return func(*args, **kwargs) 
    return wrapped 

@setup_required 
def foo(...): 
    with open(_path) as f: 
     .... 

@setup_required 
def bar(...): 
    ... 

這將是更好的包裹依賴在類路徑上雖然功能,並注入配置的對象作爲依賴,使用你想從模塊暴露API的代碼。