You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python字典关联函数传参遇NameError,如何正确实现?

How to Store and Call Functions with Parameters in a Dictionary

Hey there! Let's break down what's causing your error and how to fix this properly.

Why You're Getting the NameError

When you write mydict = {'key1':myfunc(a)}, Python immediately tries to execute myfunc(a) right at that line—not just store the function itself. Since a hasn't been defined anywhere yet, it throws the NameError. Plus, even if a existed, you'd be storing the result of myfunc(a) (which is None here, since your function only prints and doesn't return anything) instead of the function you can call later.

Solution 1: Store the Function Itself (Most Flexible)

If you want to pass different parameters when calling the function later, just store the function object in the dictionary, then pass arguments when you invoke it:

def myfunc(myval):
    print(myval)

# Store the function itself, not its call result
mydict = {'key1': myfunc}

# Call the function from the dictionary and pass your parameter
mydict['key1'](2)  # This will print 2

Solution 2: Pre-Bind Parameters with lambda

If you want to fix the parameter ahead of time (so you don't need to pass it when calling), use an anonymous lambda function to wrap the call:

def myfunc(myval):
    print(myval)

# Store a lambda that calls myfunc with your desired parameter
mydict = {'key1': lambda: myfunc(2)}

# Call the lambda (no arguments needed)
mydict['key1']()  # Prints 2

Solution 3: Pre-Bind Parameters with functools.partial

For more complex functions with multiple parameters, functools.partial is a cleaner alternative to lambda:

from functools import partial

def myfunc(myval):
    print(myval)

# Bind the parameter 2 to myfunc
mydict = {'key1': partial(myfunc, 2)}

# Call the partial function
mydict['key1']()  # Prints 2

Pick the solution that fits your use case: use Solution 1 if you need flexibility with parameters, or Solutions 2/3 if you want to fix parameters upfront.

内容的提问来源于stack exchange,提问作者ishaishai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:14:37