변수가 전달 된 후에 나중에 다른 함수를 호출하도록하는 함수를 만들 수 있습니까? 예를 들어 전달 된 인수로 명명 된 함수를 생성하는 함수
내가 get_search_engine_xml 에<engines>
<engine address="https://www.google.com/">Google</engine>
<engine address="https://www.bing.com/">Bing</engine>
<engine address="https://duckduckgo.com/">DuckDuckGo</engine>
</engines>
를 호출 그리고 여기 내 코드는 때의이 https://example.com/engine_list 반환이 XML 파일을 척 보자
import re
import requests
import xml.etree.ElementTree as ET
base_url = 'https://example.com'
def make_safe(s):
s = re.sub(r"[^\w\s]", '', s)
s = re.sub(r"\s+", '_', s)
s = str(s)
return s
# This is what I'm trying to figure out how to do correctly, create a function
# named after the engine returned in get_search_engine_xml(), to be called later
def create_get_engine_function(function_name, address):
def function_name():
r = requests.get(address)
return function_name
def get_search_engine_xml():
url = base_url + '/engine_list'
r = requests.get(url)
engines_list = str(r.content)
engines_root = ET.fromstring(engines_list)
for child in engines_root:
engine_name = child.text.lower()
engine_name = make_safe(engine_name)
engine_address = child.attrib['address']
create_get_engine_function(engine_name, engine_address)
## Runs without error.
get_search_engine_xml()
## But if I try to call one of the functions.
google()
나는 다음과 같은 오류가 발생합니다.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'google' is not defined
로그 아웃 할 때 engine_name과 engine_address를 정의하는 것이 작동하는 것 같습니다. 그래서 나는 확실히 create_get_engine_function에 문제가 있다는 것을 확신합니다. 나는 뭘하는지 몰라서 비슷한 질문에서 함께 조각하려고했습니다.
인수가 전달 된 다른 함수에서 만든 함수의 이름을 지정할 수 있습니까? 이 작업을 수행하는 더 좋은 방법이 있습니까? 당신이 실제로 성취하려는 내용에 따라 더 나은 디자인은 사전에 모든 엔진의 이름/주소를 저장하고로 접근하는 것입니다,하지만
최종 목표는 무엇입니까? –
기본적으로 앱은 사용자 입력을 받아 처리합니다. 입력은 스위치 기능으로 들어가서 무엇을해야할지 파악합니다.이 기능 중 일부는 이름으로 호출하고 일부 정적 기능은 물론 더 동적으로 만든 기능을 호출합니다. 나중에 get_search_engine_xml()을 다시 호출하고 xml이 변경된 경우 더 이상 존재하지 않는 함수를 제거하거나 반환 된 xml을 기반으로 새로운 함수를 추가해야 할 수도 있습니다. – Cynic