我正在学习python编程,我想了解一些信息。
我正在使用OOP进行一个小项目。这是项目结构的示例:
PROJECT_FOLDER
|__ main.py
|__ modules
|__ __init__.py
|__ Example.py
要导入我的类(这里只是一个,但通常更多),我应该一个一个地导入每个文件,还是应该在 __ init __。py 文件中创建一个“ all”规则?
这是我的想法:
# Example.py
class Example:
def __init__(self):
print('Hello from Example')
第一个想法:
# First version of __init__.py is an empty file
# First version of main.py
from modules.Example import Example
my_example = Example()
或者,第二个主意:
# Second version of __init__.py
__all__ = ['Example']
# Second version of main.py
from modules import *
my_example = Example.Example()
根据我在文档和此处阅读的内容,最好避免使用import *
,因为它可能会造成混淆。但是,如果需要导入56个类,是否应该在开始编码之前写56行代码来导入我的类?而且,使用import *
会迫使我写my_example = Example.Example()
,它虽然不美观,但也可能造成混淆。
最后,用类名(包括大写的首字母)来命名类文件更好吗?我了解到这是PHP的一种好习惯,但是python似乎还有其他约定(例如,蛇案),pylint总是很乐意提醒我:)
感谢您的回答,祝您愉快!