Python import 及项目目录架构 使用总结

假设文件结构是

parent/
        yz/<br>
                 __init__.py
                  test2.py
        test1.py
        test2.py

/test2.py

i = 2
def function():
    print 123
    a = 'hello'
class ClassName(object):
    """docstring for ClassName"""
    def __init__(self, arg):
        super(ClassName, self).__init__()
        self.arg = arg

yz/test2.py

# -*- coding:utf8 -*- 
'''wer'''
a = 37                    
def foo():
    print "I'm foo"
class bar:               
    def grok(self):
        print "I'm bar.grok"
b = bar()               

import 同一文件夹下的文件

test1 引用 test2

import test2
print test2.i
test2.function()
b = test2.bar()
from test2 import i
print i

import 文件名
仅仅是把文件名引到了python的命名空间
利用.寻找其中的值

import 不同文件夹下的文件

test1 引用 yz/test2
注意这时必须在/yz文件中设置init.py(才能把文件夹识别为目录)

from yz.test2 import a
print a
from yz import test2
print test2.a

__init__.py的作用

  偶尔可以看到有些人写的包下面还会有一个__init__.py,它的作用是在导入包时首先执行的。

if __name__ == “__main__”

  也有时候会看到 .if __name__ == "__main__" 语句,它的作用就是当此文件没有被作为导入的文件使用时执行 if 语句块里的程序。

  假如 exp.py 中加入了 **if __name__ == "__main__"** ,然后 **python3 exp.py**,就会执行这个语句块里的内容

  而 如果** if __name__ == "exp"**,时则是被 其他文件 以** "import exp"**导入时执行的部分

  有如果是** if __name__ == "one.exp"**,时则是被 其他文件 以** "import one.exp"**导入时执行的部分

  注意 在  "import exp"时是不会执行 if __name__ == "one.exp"中的内容的!同样: "import one.exp“是不会执行 if __name__ == "exp"中的内容的

项目目录架构

假设你的项目名为foo, 我比较建议的最方便快捷目录结构这样就足够了:

Foo/
|-- bin/
|   |-- foo
|
|-- foo/
|   |-- tests/
|   |   |-- __init__.py
|   |   |-- test_main.py
|   |
|   |-- __init__.py
|   |-- main.py
|
|-- docs/
|   |-- conf.py
|   |-- abc.rst
|
|-- setup.py
|-- requirements.txt
|-- README

简要解释一下:


    bin/: 存放项目的一些可执行文件,当然你可以起名script/之类的也行。
    foo/: 存放项目的所有源代码。
        (1) 源代码中的所有模块、包都应该放在此目录。不要置于顶层目录。
        (2) 其子目录tests/存放单元测试代码;
        (3) 程序的入口最好命名为main.py。
    docs/: 存放一些文档。
    setup.py: 安装、部署、打包的脚本。
    requirements.txt: 存放软件依赖的外部Python包列表。
    README: 项目说明文件。
发布了99 篇原创文章 · 获赞 51 · 访问量 71万+

猜你喜欢

转载自blog.csdn.net/qq_31481187/article/details/68931104
今日推荐