提取字典字段以用作函数名称

Pulling out a dictionary field to use as a function name

我正在尝试通过引用字典使用 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))

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

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

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

有什么方法可以提取字典中字段的名称,使其成为一个函数吗?

你可以做到

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)}

因为你实际上是将一个函数复制到多个具有不同名称的函数中,并在你的评论中验证这一点 "use different names but that are all inherently the same",我认为最简单的方法是先定义你的基本函数,然后将它复制到您想要的许多不同的新功能。像这样:

您的基函数总是返回 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