根据字典的键生成函数

  • 本文关键字:函数 字典 python-3.x
  • 更新时间 :
  • 英文 :


对于使用prompt_tookit创建的脚本,我想添加一些服务。为此,我需要为每个服务创建一个新函数。我想使用dict的键和值来生成这个函数,因为所有的函数几乎都是相同的。

我的字典

services_dict={
'service_1':'apache2',
'service_2':'gdm.service',
'service_3':'ARLV',
'service_4':'ARLV_Frontend'}
for key,val in services_dict.items():
def key():
service_text_area.text='{}'.format(val)

它应该生成这样的函数:

def service_1():
service_text_area.text='apache2'
def service_2():
service_text_area.text='gdm.service'

在python中有这样的方法吗?

您可以使用exec内置来执行函数定义:

services_dict={
'service_1':'apache2',
'service_2':'gdm.service',
'service_3':'ARLV',
'service_4':'ARLV_Frontend'}
for key,val in services_dict.items():
exec('def ' + key + '():n' + 'tservice_text_area.text = "' + val + '"')

最新更新