整理我的Python项目

整理我的Python项目

本文介绍了整理我的Python项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在启动一个Python项目,并希望其中有20个或更多类.按照惯例,我想将它们分别放在一个单独的文件中.但是,项目目录很快就会被文件淹没(或者当我这样做时也会被淹没).

I'm starting a Python project and expect to have 20 or more classes in it. As is good practice I want to put them in a separate file each. However, the project directory quickly becomes swamped with files (or will when I do this).

如果我将要导入的文件放在文件夹中,则无法再导入它.我如何从另一个文件夹导入文件,并且由于它位于一个文件夹中,所以我需要引用它所包含的类吗?

If I put a file to import in a folder I can no longer import it. How do I import a file from another folder and will I need to reference to the class it contains differently now that it's in a folder?

预先感谢

推荐答案

在您的项目文件夹中创建一个__init__.py文件,Python会将其视为模块.

Create an __init__.py file in your projects folder, and it will be treated like a module by Python.

然后可以使用以下语法导入包目录中的类:

Classes in your package directory can then be imported using syntax like:

from package import class
import package.class

__init__.py内,您可以创建定义from package import *行为的__all__数组:

Within __init__.py, you may create an __all__ array that defines from package import * behavior:

# name1 and name2 will be available in calling module's namespace
# when using "from package import *" syntax
__all__ = ['name1', 'name2']

这是更多信息,甚至比您想了解的Python包还要多

通常来说,了解如何组织大量代码的一个好方法是选择一个流行的Python包,然后看看他们是如何做到的.我会查看 Django 扭曲,适合初学者.

Generally speaking, a good way to learn about how to organize a lot of code is to pick a popular Python package and see how they did it. I'd check out Django and Twisted, for starters.

这篇关于整理我的Python项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:47