我有两个文件,app.py
和database.py
在同一目录中。 主要是我有下面的代码片段:导入有和没有主要范围
app.py
import database
db = "demo_database"
print(database.show_database_information())
database.py
from app import db
database_username = "root"
database_password = "password"
def show_database_information():
information = {}
information["filename"] = db
information["username"] = database_username
information["password"] = database_password
return information
当我尝试运行app.py
我得到了以下错误:
Traceback (most recent call last):
File "K:\PyPrac\circular_call\app.py", line 1, in <module>
import database
File "K:\PyPrac\circular_call\database.py", line 1, in <module>
from app import db
File "K:\PyPrac\circular_call\app.py", line 3, in <module>
print(database.show_database_information())
AttributeError: module 'database' has no attribute 'show_database_information'
然后我更新app.py
并列入__main__
检查象下面这样:
app.py
import database
db = "demo_database"
if __name__ == '__main__':
print(database.show_database_information())
现在,运行流畅,没有任何错误。
我有几个问题,
- 是发生了什么错误的名字在第一种情形?需要解释。
- 为什么在包含
__main__
范围后运行? - 做这种操作的更好方法是什么?
我知道它正在创建循环导入,但是它如何使用主范围来解决? – arsho
@arsho我已经更新了我的答案。我希望它能帮助你。 –
它是一个热修复,但现在函数被调用两次。 '''{'filename':'database.sqlite','username':'root','password':'password'} {'filename':'database.sqlite','username':'root', '密码':'密码'}'''感谢您的更新。 – arsho