0

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

文件1.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)

stringvariable1,在第一个函数调用中使用,是一个局部变量,file1.py因此可以作为函数中的参数访问。它故意与后来在该参数位置使用的变量不同。

文件2.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比上面显示的更复杂,为了简洁起见,只是这样演示。

问题发生在第二次调用replacefunctionin 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

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

有没有办法从函数外部访问变量,明确地作为变量而不是通过分配给函数?

4

1 回答 1

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,然后传递给第二个调用。第二次函数调用的返回值再次被存储(这里使用相同的名称),并传递给第三次调用。等等。

于 2013-11-02T16:05:20.463 回答