【问题标题】:how to use a for loop to create functions? python如何使用 for 循环创建函数? Python
【发布时间】:2019-01-29 21:15:50
【问题描述】:

我需要使用 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

【问题讨论】:

  • 您所做的是每次都定义一个名为resource 的新函数。所以,没有food这样的功能
  • 这可能是可能的,但不是一个好主意。您是否愿意接受有关获得相同结果的另一种方法的建议?
  • stackoverflow.com/questions/3431676/… 这可能对你有帮助
  • @mypetlion 是的!当然。

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


【解决方案1】:

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

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 次
  • 你创建了 5 次 json

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

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

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多