[英]Python how to call a class method from a string that contains parameters
I have the following code.我有以下代码。 What would be the best way to evaluate the command variable and the parameters it contains.评估命令变量及其包含的参数的最佳方法是什么。
This is a contrived example, but the easiest way to explain what I am trying to do on a bigger scale.这是一个人为的例子,但最简单的方法来解释我正在尝试在更大范围内做什么。
class Job():
def random_number(self, start, end, prec=0):
number = round(random.uniform(start,end),prec)
if(prec == 0):
return int(number)
return number
def run(self, command):
#command = "self.random_number(1,10,0)"
#**************
# What would be the best way to 'eval' the content of the 'command' variable and the parameters it contains?
#**************
job = Job()
job.run("self.random_number(1,10,0)")
Generally, this seems a bad idea, consider restructuring your code.一般来说,这似乎是一个坏主意,请考虑重组您的代码。 That said, you may make use of getattr(...)
in combination with splitting your string into a function and a params part:也就是说,您可以结合使用getattr(...)
将字符串拆分为 function 和 params 部分:
import random, re
class Job():
def random_number(self, start, end, prec=0):
number = round(random.uniform(start, end), prec)
if (prec == 0):
return int(number)
return number
def run(self, command):
fun, params, _ = re.split(r'[()]', command)
params = map(int, params.split(","))
func = getattr(Job, fun)
print(func(*params))
job = Job()
job.run("random_number(1,10,0)")
Obviously, you'd need to add some error management (broken strings, functions, that don't exist, floats instead of integers - you get the idea).显然,您需要添加一些错误管理(损坏的字符串、不存在的函数、浮点数而不是整数——您明白了)。
You can use the eval()
function like so:您可以像这样使用eval()
function:
def run(self, command):
return eval(command)
would this work for you?这对你有用吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.