【问题标题】:Pulling out a dictionary field to use as a function name提取字典字段以用作函数名称
【发布时间】:2019-07-14 14:08:23
【问题描述】:

我正在尝试通过引用字典来使用 for 循环创建函数。

我的两次不同的尝试都没有成功:

dictionary = {1:'Apples', 2:'Pears', 3:'Carrots'}

for i in range(1, 4, 1):
    name = dictionary[i]
    def name(price, quantity):
        total = price*quantity
        return total

print(Apples(3, 2))

此方法不成功,因为“名称”成为正在定义的函数名称。 (名称错误)

for i in range(1, 4, 1):
    def dictionary[i](price, quantity):
        total = price*quantity
        return total

此方法不成功,因为在定义函数时方括号被视为语法错误。

有没有办法可以提取字典中字段的名称以使其成为函数?

【问题讨论】:

  • 为什么需要这样做? 4 个不同名称的相同函数有什么意义?
  • 我正在简化情况以便获得尽可能明确的答案,关于我的实际问题,我将使用此解决方案在 Tkinter 中创建多个页面,这些页面使用不同的名称,但本质上都是一样的。
  • 您知道字典值可以是函数,对吧?换句话说,可能没有理由将函数的名称存储在字典中。
  • @martineau 请详细说明,我不遵循您的意思,因为我在问题中试图做的是在函数中使用字典值。即def dictionary[i] = def apples
  • @Matt:我的意思是dict 可以将键映射到(预先存在的)函数。例如如果您有一个名为my_func() 的已定义函数,您可以创建一个包含{'Plums': my_func} 的字典。事实上,您甚至可以将它与另一个键(在相同或不同的字典中)关联,即{'Plums': my_func, 'Prunes': my_func}。然后可以通过dictionary['Plums']()dictionary['Prunes']() 调用该函数。如需更具体的答案,请发布另一个问题。注意我怀疑这可能是所谓的XY Problem

标签: python function dictionary user-defined-functions python-3.7


【解决方案1】:

由于您实际上是将一个函数复制到具有不同名称的多个函数中,并在您的评论中验证这一点“使用不同的名称但本质上都是相同的”,我认为最简单的方法是首先定义您的基本函数,并将其复制到您想要的许多不同的新功能中。像这样:

你的基本函数总是返回price*quantity,所以让我们定义它:

def base_fun(price, quantity):
    total = price*quantity
    return total

现在让我们将其克隆到您的字典项中:

import copy

for k, v in dictionary.items():
  globals()[v] = copy.copy(base_fun)

print(Apples(3, 2)) #returns 6
print(Pears(5, 4)) #returns 20
print(Pears(0, 3)) #returns 0

【讨论】:

    【解决方案2】:

    你可以的

    for i in range(1, 4, 1):
        name = dictionary[i]
        def _fn(price, quantity):
            total = price*quantity
            return total
        globals()[name] = _fn
    

    但很少需要这样做。

    执行此操作的更明智的方法(如@martineau 所述)是将函数直接放入字典中:

    def Apples(price, quantity):
        total = price * quantity
        return total
    
    def Pears(...): ...
    def Carrots(...): ...
    
    dictionary = {1: Apples, 2: Pears, 3: Carrots}
    

    你会这样调用函数:

    dictionary[1](price=2.50, quantity=4)
    

    如果你将dictionary 重命名为total,它的可读性会更好:

    product_id = 1
    total_price = total[product_id](price=2.50, quantity=4)
    

    如果所有功能都相同,那就更容易了:

    def totalfn(price, quantity):
        total = price * quantity
        return total
    
    total = {1: totalfn, 2: totalfn, 3: totalfn}
    

    如果您有很多产品,甚至更短:

    total = {productid: totalfn for productid in (1,2,3)}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      • 2020-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多