Python导入模块后触发Function not defined错误,求排查原因
The issue here boils down to how Python handles module namespaces. When you use import mym, you’re importing the entire module, but its functions aren’t added directly to your script’s global scope—they’re nested under the mym module name. That’s why calling hello() or summ() directly throws a NameError; Python doesn’t recognize those names in your script’s current context.
Solution 1: Access Functions via the Module Namespace
Modify your abc.py to prefix each function call with the module name. This tells Python exactly where to find the functions:
import mym mym.hello() x = mym.summ(3,4) print(x)
Solution 2: Import Specific Functions Directly
If you prefer to call functions without the module prefix, use the from ... import syntax to pull them into your script’s global scope explicitly:
from mym import hello, summ hello() x = summ(3,4) print(x)
Bonus: Import All Functions (Not Recommended)
You can import every function from the module with this shortcut, but it’s generally discouraged because it can cause name conflicts and reduce code readability in larger projects:
from mym import * hello() x = summ(3,4) print(x)
To confirm, here are the errors these fixes resolve:
Traceback (most recent call last):
File "C:/Users/Nisha/AppData/Local/Programs/Python/Python39/abc.py", line 3, in
hello()
NameError: name 'hello' is not defined
Traceback (most recent call last):
File "C:/Users/Nisha/AppData/Local/Programs/Python/Python39/abc.py", line 3, in
x=summ(3,4)
NameError: name 'summ' is not defined
内容的提问来源于stack exchange,提问作者Nisha B

