如何使用列表项的名称创建函数,
Posted
技术标签:
【中文标题】如何使用列表项的名称创建函数,【英文标题】:How to create functions with a name of the list item, 【发布时间】:2021-01-18 14:32:22 【问题描述】:在 kivy 应用程序中,它在启动时接收一个 json 值,将它们分配给一个变量并将它们附加到一个列表中。在每次应用启动时,它都会收到不同的值,因此列表总是不同的。
Ch1_name = channel.json()['items']['channels'][0]['channelName']
Ch2_name = channel.json()['items']['channels'][1]['channelName']
Ch3_name = channel.json()['items']['channels'][2]['channelName']
Ch4_name = channel.json()['items']['channels'][3]['channelName']
channels = []
channels.append(Ch1_name)
channels.append(Ch2_name)
channels.append(Ch3_name)
channels.append(Ch4_name)
print(channels)
['cnn','fox','sky sports','fsc']
问题: 我需要为每个频道创建函数,这将保留作为频道名称的列表项的名称。比如:
def cnn()
print('this function was named cnn just like an item list')
也许有一个不同的方式来做一个类?感谢您的任何想法。
【问题讨论】:
【参考方案1】:for channel_name in channels:
exec(f"""
def channel_name():
print(f'this function was named channel_name just like an item list')
"""
)
【讨论】:
非常感谢,非常简单的解决方案!【参考方案2】:你可以做一些元编程的东西来动态添加函数。下面是一些示例代码,它使用setattr
根据通道名称在类上设置函数。
class ChannelPrinter:
pass
channel_printer = ChannelPrinter()
for channel in ['cnn', 'fox', 'sky sports', 'fsc']:
def make_func(name):
def print_channel_info():
print('this function was named just like an item list'.format(name))
return print_channel_info
setattr(channel_printer, channel, make_func(name=channel))
> channel_printer.cnn()
this function was named cnn just like an item list
> channel_printer.fox()
this function was named fox just like an item list
【讨论】:
以上是关于如何使用列表项的名称创建函数,的主要内容,如果未能解决你的问题,请参考以下文章
创建一个列表元素,并使用用户输入的内容(使用javascript)为它上色