使用Python中的多个代码文件和文件夹 [英] Working with multiple code files and folders in Python
问题描述
我是Python的新手,我还没有找到一种在多个代码文件和文件夹中分隔代码的简单方法。
I am new to Python and I haven't figured out a simple way of separating code in multiple code files and folders.
我今天所做的是:for每个文件夹我创建一个 __ init __。py
文件。有时它是空的。我不知道为什么要这样做,但似乎有必要。这是与使用C#的第一个区别。
What I do today is: for each folder I create an __init__.py
file. Sometimes it's empty. I don't know why I do it, but it seems necessary. That's the first difference from working with C#.
第二个区别是,对于任何另一个文件,我必须使用导入,例如 model.table导入表
。如果我有多个引用,我需要使用多个导入:
The second difference is that for any file to reference any another I must use an import, like from model.table import Table
. And if I have multiple references I need to use multiple imports:
from model import table1,table2
然后在其余的代码中我必须使用 table1.Table1
per例。如果我不想,我应该
and then in the rest of the code I must use table1.Table1
per example. If I don't want to, I should
from model.table1 import Table1
from model.table2 import Table2
然后我可以简单地使用 Table1
and then I can use simply Table1
这与我在C#中的习惯有很大不同,如果所有文件都在同一名称空间中,我们没有进口
。对我来说有更简单的方法吗?
That differs too much from what I'm used to in C#, where if all files were in the same namespace, we didn't have to import
. Is there a simpler way for me?
推荐答案
您应该阅读模块: http://docs.python.org/tutorial/modules.html
基本上,我认为你没有正确组织你的代码。使用python,目录和文件都有意义;它不仅仅是你写入文件的内容。对于每个新目录(使用 __ init __。py
)和每个新文件,您创建一个新的命名空间......
Basically, I think you aren't organizing your code right. With python, directories and files have a meaning; it's not just what you write into the files. With every new directory (with __init__.py
) and every new file you create a new "namespace"...
如果你有文件 /mydatabase/model.py
和 Table1
,<$ c在$
If you have the file /mydatabase/model.py
and the Table1
, Table2
, etc defined in that model.py
file you can simply:
from mydatabase.model import *
不要创建每个表
类的新文件!
Do not create a new file for each Table
class!
这篇关于使用Python中的多个代码文件和文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!