如何使用for循环创建函数?蟒蛇

时间:2019-01-29 21:15:51

标签: python-3.x function for-loop

我需要使用for循环创建多个函数,以便我可以使用不同的名称使用相似的函数。

rss = ['food', 'wood', 'stone', 'iron', 'gold']

for resource in rss:
    def resource(account):
        with open('accountdetails.py', 'r') as file:
            accdets = json.load(file)
        rss_value = accdets[account][resource]
        print(rss_value)

food('account_3')

此代码不起作用,但是我希望它创建5个不同的函数,根据调用的函数替换[resource]。相反,我得到NameError: name 'food' is not defined

1 个答案:

答案 0 :(得分:0)

您不能创建这样的功能-但是,您可以重用相同的功能,并简单地提供“资源名称”作为其附加输入:

def resource(account, res):
    """Prints the resource 'res' from acccount 'account'"""
    with open('accountdetails.py', 'r') as file:
        accdets = json.load(file)
    rss_value = accdets[account][res]
    print(rss_value)


rss = ['food', 'wood', 'stone', 'iron', 'gold']
for what in rss:
    resource("account_3", what) # this will print it 

缺点是:

  • 您加载文件5次
  • 您将json创建了5次

最好只进行一次加载和创建对象:

# not sure if it warrants its own function
def print_resource(data, account, res):
    print(data[account][res]) 

# load json from file and create object from it 
with open('accountdetails.py', 'r') as file:
    accdets = json.load(file)

rss = ['food', 'wood', 'stone', 'iron', 'gold']
for what in rss:
    print_resource(accdets, "account_3", what)