[英]Convert string into variable name python
I have the below code.我有下面的代码。 Is this an ok way to do this?
这是一个好的方法吗? I'm wanting to make the dictionary a bit smaller by doing something more like
if exec(f"self.{script}"):
and only store the script name with the function reference, but that doesn't seem to work and just provides a none.我想通过做一些更像
if exec(f"self.{script}"):
并且只使用 function 引用存储脚本名称来使字典更小一些,但这似乎不起作用,只是提供无。 I think I would be ok with this current solution, but I'm not sure if it could be improved.我想我会接受这个当前的解决方案,但我不确定它是否可以改进。
scripts = {
"script1": {
"run": self.script1,
"function": self.run_script1},
"script2": {
"run": self.script2,
"function": self.run_script2},
}
for script in scripts:
if scripts[script]["run"]:
try:
scripts[script]["function"]()
except Exception as e:
self.send_error_msg(f"{script} caused an exception: \"{e}\", continuing with next script.")
Since you're just iterating over every element in the dictionary, having it as a dictionary with specific keys isn't providing any benefit.由于您只是迭代字典中的每个元素,因此将其作为具有特定键的字典并没有提供任何好处。 I'd suggest just having a list of tuples:
我建议只列出一个元组:
scripts = [
(self.script1, self.run_script1),
(self.script2, self.run_script2),
]
for should_run, function in scripts:
if should_run:
try:
function()
except Exception as e:
self.send_error_msg("...")
If you want objects with named attributes instead of tuples whose order you have to keep track of, I'd suggest using a small dataclass
rather than a dict:如果您想要具有命名属性的对象而不是您必须跟踪其顺序的元组,我建议使用小型
dataclass
而不是字典:
from dataclasses import dataclass
from typing import Callable
@dataclass
class Script:
run: bool
function: Callable[[], None]
scripts = [
Script(self.script1, self.run_script),
Script(self.script2, self.run_script2),
]
for script in scripts:
if script.run:
try:
script.function()
except Exception as e:
self.send_error_msg("...")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.