要求用户在Python中输入一个函数。

huangapple go评论61阅读模式
英文:

Asking the user to enter a function in python

问题

我正在制作一个使用牛顿法计算任何函数的解f(x)=0的Python程序。是否可以要求用户输入函数?

我的伪代码:

要求输入一个函数

创建一个函数:def Newton(Myfunction, initial_value)

英文:

I am making a python program that computes the solution of f(x) =0 with Newton method, for any function. Is it possible to ask the user to enter the function?

my pseudo code :

# ask for a function

# create a function with: def Newton(Myfunction, initial_value)

答案1

得分: 1

你可以要求用户输入包含函数定义的Python文件的名称,还可以要求输入函数的名称。然后在你的主文件中,你可以像这样操作:

import importlib
source = importlib.import_module(filename)
func = getattr(source, function)

就像这个答案中所示,其中 function 是你的用户函数的名称,然后从主文件中调用该函数。你可以像这样接受用户输入:

filename = input("请输入包含函数的文件名")

但是这种方法存在安全风险,因为用户可以以这种方式输入文件中的任何函数(如下面的评论中所指出的)。

英文:

You can ask the user to input the name of the python file that contains the function definition and also ask for the name of the function. Then inside your main file you can do

import importlib
source = importlib.import_module(filename)
func = getattr(source, function)

like in this answer where function is the name of your user function and then call the function from your main file. You can take user input as

filename = input("Please enter filename containing function")

However there's a security risk in this method as the user can input any function from the file this way (as noted in the comment below)

huangapple
  • 本文由 发表于 2020年1月3日 17:40:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576168.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定