有没有办法从函数外部访问变量,显式地作为变量而不是通过赋值给函数?

时间:2013-11-02 15:58:08

标签: python function variables python-2.7 dictionary

我想用关联字典中的值替换关键字。

file1.py

import file2

file2.replacefunction('Some text','a_unique_key', string_variable1)
file2.replacefunction('Other text','another_unique_key', string_variable2)
file2.replacefunction('More text','unique_key_3', string_variable2)
在第一个函数调用中使用的

stringvariable1file1.py中的局部变量,因此可以作为函数中的参数访问。故意是与后面在该参数位置中使用的变量不同的变量。

file2.py

import re

keywords = {
    "a_unique_key":"<b>Some text</b>",
    "another_unique_key":"<b>Other text</b>",
    "unique_key_3":"<b>More text</b>",
}

def replacefunction(str_to_replace, replacement_key, dynamic_source):
    string_variable2 = re.sub(str_to_replace, keywords[replacement_key], dynamic_source)
    return string_variable2  <-- this variable needs to be accessible

keywords字典中的替换值比上面显示的更复杂,为简洁起见,这样说明就是这样。

问题发生在replacefunction中第二次调用file1.py时 - 它无法访问stringvariable2,这是第一个运行的函数的结果。

我已经看到访问该函数之外的函数中生成的变量的方法是执行以下操作:

def helloworld()
    a = 5
    return a

mynewvariable = helloworld()

print mynewvariable

5  <-- is printed

但是这种方法在这种情况下不起作用,因为函数需要处理每个函数调用后更新的字符串,即:

do this to string 2 # changes occur to string 2
do this to string 2 # changes occur to string 2
do this to string 2 # changes occur to string 2

我可以在没有功能的情况下实现所需的功能,但只是尝试最小化代码。

有没有办法从函数外部访问变量,显式地作为变量而不是通过赋值给函数?

1 个答案:

答案 0 :(得分:1)

不要将变量与混淆。名称string_variable2引用了一个值,您只需从函数中返回该值。

调用函数的地方,将返回的值赋给局部变量,并使用该引用将其传递给下一个函数调用:

string_variable2 = file2.replacefunction('Some text','a_unique_key', string_variable1)
string_variable2 = file2.replacefunction('Other text','another_unique_key', string_variable2)
file2.replacefunction('More text','unique_key_3', string_variable2)

此处replacefunction返回某些,存储在string_variable2中,然后传递给第二个调用。再次存储第二个函数调用的返回值(在此使用相同的名称),并传递给第三个调用。等等。