"AttributeError: 'module' object has no attribute [duplicate]": A Comprehensive Guide
This error occurs when a Python module attempts to access an attribute that doesn't exist. In your specific case, the error is "AttributeError: 'module' object has no attribute 'hi'". This error indicates that the module you're importing (b.py) doesn't have a function named 'hi'.
Understanding Mutual Top-Level Imports
The issue arises because you have mutual top-level imports between a.py and b.py. This is generally not recommended, as it can lead to circular imports and other problems.
Solving the Issue
To fix this error and avoid mutual imports, you can import the modules within functions as follows:
In b.py:
<code class="python">def cause_a_to_do_something(): import a a.do_something()</code>
In a.py:
<code class="python">import b def hello(): print("hello") print("a.py") print(hello()) b.cause_a_to_do_something()</code>
This way, a.py can safely import b.py and call its functions without causing any errors.
Import Optimization
While it may seem inefficient to import within a function, it's actually not. Python caches imported modules, so the import operation is only performed the first time you call the function. Subsequent imports are a quick operation.
The above is the detailed content of Why does \'AttributeError: \'module\' object has no attribute [duplicate]\' Occur?. For more information, please follow other related articles on the PHP Chinese website!