Python3传递函数对象作为参数遇TypeError报错,求解决方案
Hey there! Let's break down this error you're facing when working with function objects in Python 3. This issue usually boils down to one of two common mistakes—let's walk through them step by step.
1. You Accidentally Overrode the Built-in print Function
The most likely culprit here is that you created a custom function named print (without any parameters) which replaces Python's built-in print function. When you pass this custom function as an argument and try to call it with a parameter, it throws the error because your version doesn't accept any inputs.
Example of the Problem:
# Oops! This custom print function has no parameters and overrides the built-in one def print(): print("My custom print message") def run_func(func): # We try to pass an argument to the function we received func("Trying to send this text") # Passing our custom print function triggers the error run_func(print)
Fixes:
- Rename your custom function: Pick a unique name like
my_printinstead of usingprintto avoid conflicting with built-ins. - Restore the built-in print: If you need to get the original
printback, you can do this:import builtins print = builtins.print # Resets print to Python's default function
2. You're Passing a Function Call (Not the Function Object)
Another possible mistake is adding parentheses when passing the function—this calls the function immediately and passes its return value (which is None for print()) instead of the function itself. While this usually throws a 'NoneType' object is not callable error, edge cases might trigger your specific message.
Example of the Problem:
def execute_function(func): func("Test input") # Wrong: We're passing print() (the result of calling print) instead of print the function execute_function(print())
Fix:
- Remove the parentheses when passing the function. Just use the function name to pass the object itself:
execute_function(print) # Correct way to pass the print function
Quick Check to Diagnose
Add this line to your code to see what print actually is:
print(type(print))
- If it outputs
<class 'function'>but your code still throws the error, you definitely overrode the built-inprint. - If it outputs
<class 'NoneType'>, you're passing the result of a function call instead of the function object.
Hopefully one of these fixes resolves your issue!
内容的提问来源于stack exchange,提问作者Edge Waters

