사용자 입력에서 함수를 호출 할 수 있습니까? 다음과 같은 것 :사용자 입력에서 파이썬 호출 함수
def testfunction(function):
function()
a = raw_input("fill in function name: "
testfunction(a)
그래서 기존 함수를 채우면 실행하게됩니다.
사용자 입력에서 함수를 호출 할 수 있습니까? 다음과 같은 것 :사용자 입력에서 파이썬 호출 함수
def testfunction(function):
function()
a = raw_input("fill in function name: "
testfunction(a)
그래서 기존 함수를 채우면 실행하게됩니다.
예, 이것은 일반적으로 나쁜 아이디어이며 큰 보안 위험입니다.
def testfunc(fn):
fn()
funcname = raw_input('Enter the name of a function')
if callable(globals()[funcname]):
testfunc(globals()[funcname])
당신이하고있는 일은 나쁘지 않은 나쁜 일입니다. 그러나 완벽하게 가능합니다.
a = raw_input("Fill in function name:")
if a in locals().keys() and callable(locals()['a']):
locals()['a']()
else:
print 'Function not found'
locals()
모든 현재 avalible 개체 및 이름의 사전을 반환합니다. 그래서 우리가 a in locals().keys()
라고 말할 때 우리는 "어떤 객체가 있는지"라고 말하고 있습니다. 있을 경우 locals()['a']
을 실행하여 얻은 다음 callable
을 사용하는 함수인지 테스트합니다. 그 값이 True
이라면 함수를 호출합니다. 그렇지 않으면 단순히 "Function not found"
을 인쇄합니다.
아마 수업 시간에 행동의 종류를 캡슐화 것 :
다른 사람이 말했듯이class UserExec(object):
def __init__(self):
self.msg = "hello"
def get_command(self):
command = str(raw_input("Enter a command: "))
if not hasattr(self, command):
print "%s is not a valid command" % command
else:
getattr(self, command)()
def print_msg(self):
print self.msg
a = UserExec()
a.get_command()
, 이것은 보안 상 위험하지만, 더 많은 제어 당신은 입력을 통해이 위험의 덜 이다; 신중한 입력 검사가 포함 된 수업에 참여하면 도움이됩니다.
이 절차 버전은 무엇입니까? 파이썬 3.x는 전혀 달라 보이나요? –
@ArashHowaida 약간 다르지만, 기본적인 것, 예기치 않은 것, 이례적인 것 -이 경우에는 단지'print'와'raw_input'만이 변할 필요가 있습니다. 나는 항상 사람들이 [여기] (https://docs.python.org/3/whatsnew/3.0.html)의 차이점에 익숙해 지도록 조언합니다. – senderle