【问题标题】:way to create fstring inside a fstring在 fstring 中创建 fstring 的方法
【发布时间】:2018-06-26 09:53:38
【问题描述】:

是否可以在 fstring 中创建 fstring?

我现在正在尝试使用 eval 创建一个动态函数。

我的代码是这样的

func_string = ''
for scenario in ['scene1', 'scene2']:
    for aa in ['int', 'ext']:
         func_string += f'''
             def function_{scenario}_{aa}(part):
                 print(f"this is {part}")
           '''


eval(func_string)
function_scene1_int('part1')

运行此脚本将返回: 这是第 1 部分

【问题讨论】:

  • 您需要使用eval吗?
  • 它应该返回什么?它成功地将 {part} 替换为“part1”
  • 我需要动态创建 30 个函数,你有什么建议我可以在不明确编码所有这些函数的情况下做到这一点
  • 它可以工作,但它是一种反模式。变量或函数的动态创建(几乎)总是无法解决实际问题。
  • Serge Ballesta,你有没有更好的建议来创建30个回调函数,如dash.plot.ly/getting-started-part-2的第一个示例所示?

标签: python string f-string


【解决方案1】:

你可以制作这样的工厂方法...

def factory(a, b):
    def g(c):
        print(f'this is {c}')
        return f'other stuff using {a}, {b} and {c}'  # if you want to
    return g

然后像这样使用它

>>> f = factory('scene1', 'int')
>>> msg = f('part1')
this is part1
>>> print(msg)
other stuff using scene1, int and part1

【讨论】:

  • 啊哈...我能闻到答案...:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-06
  • 1970-01-01
  • 2021-04-08
  • 2023-01-18
  • 2018-09-09
  • 2022-11-29
相关资源
最近更新 更多