키워드를 연관된 사전의 값으로 대체하려고합니다. 제 1 함수 호출에 사용함수 외부에서 변수에 명시 적으로 액세스 할 수있는 방법이 있습니까? 함수에 할당하지 않고 변수로 명시 적으로 액세스 할 수 있습니까?
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는 file1.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
사전에 여분의 값은 더 복잡하다.
file1.py
에 replacefunction
에 대한 두 번째 호출에서 문제가 발생합니다. 실행되는 첫 번째 기능의 결과 인 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
.
함수 외부에서 변수에 명시 적으로 액세스 할 수 있습니까? 함수에 할당하지 않고 변수로 명시 적으로 액세스 할 수 있습니까?
저는 파이썬에서'global'의 존재를 알려주는 것에 대해 죄책감을 느낍니다. 내부 상태를 유지해야하는 경우 개체가 필요한 것입니다. –