Why does \'AttributeError: \'module\' object has no attribute [duplicate]\' Occur?

Mary-Kate Olsen
Release: 2024-10-20 12:55:02
Original
726 people have browsed it

Why does

"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>
Copy after login

In a.py:

<code class="python">import b

def hello():
    print("hello")

print("a.py")
print(hello())
b.cause_a_to_do_something()</code>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!