Python字典关联函数传参遇NameError,如何正确实现?
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

