In my introduction to python course we were covering the input function last time and I saw that whatever you type as an input is stored as a string. You can use the int() and float() before the input function to store as a number but I was wondering how can it be used to store a function the user enters. Is there a way to use input to allow me to define a function?
答案 0 :(得分:1)
You can do this using the exec()
built in function.
https://docs.python.org/3/library/functions.html#exec
my_function_def = '''
def my_function():
print('Greetings from my function!')
'''
exec(my_function_def)
my_function() # -> 'Greetings from my function!'
答案 1 :(得分:1)
One potential solution is to allow the user to call a pre-defined method by name. This is more secure than using the exec()
command outright, as it strictly limits the user's ability to trigger code blocks.
def SomeAction():
print("SomeAction has been executed.")
userInput = input("Enter method name: ")
if(userInput == SomeAction.__name__):
method = getattr(sys.modules[__name__], SomeAction.__name__) #Get method by name
method()
However, if you're talking about having the user define a method completely from input
calls, then you'll need to create an input
loop to get the method body.
print("Enter your method declaration: ")
methodDeclaration = ""
methodLine = "X"
i = 1
while(len(methodLine) != 0):
methodLine = input(str(i) + ": ")
i = i+1
methodDeclaration = methodDeclaration +"\n"+ methodLine
print("Method to be executed:")
print(methodDeclaration)
exec(methodDeclaration)
myMethod()
The output of the above code is as below:
Enter method name: SomeAction
SomeAction has been executed.
Enter your method declaration:
1: def myMethod():
2: print("MyMethod is running!")
3:
Method to be executed:
def myMethod():
print("MyMethod is running!")
MyMethod is running!
Be advised that this is not a secure practice. Using exec()
allows the user to input any desired command into your python script. That being said, it is indeed possible to have user-defined methods from input.
答案 2 :(得分:0)
def A(arg):
"""function definations """
return arg
def B(func):
""" function defination B with func as argument """
return func(input())
B(A)
more ref: Python function as a function argument?