正常工程中,代码需要分模块来进行存储。
例如在hello.py文件中:
- def print_hello():
- print("hello")
在另一个文件main.py中使用hello.py 中的print_hello函数可以用import直接引用hello文件:
- import hello
- hello.print_hello()
也可以使用from来引用,from只能一次引用一个函数,然后直接使用函数:
- from hello import print_hello()
- print_hello()
以上两种只能在同一文件夹下才能有效,如果不在同一文件夹中,需要用sys模块:
- import sys
- sys.path.append('.........') #路径
- import hello
- hello.print_hello
sys.path是一个列表,列表中是python用来调用第三方模块使用的文件,如果我们需要调用自己的模块,需要加入自己模块的路径到这个列表中,同理用insert也可以。值得注意的是Windows的文件目录用的是\号隔开,python中需要用/隔开。
包
当我们需要调用的模块很多,而且又在同一个文件夹里时。就需要加入很多路径,这样就会很浪费时间。因此我们将模块集合在一个文件夹下,叫做包。调用一个包后,可以直接调用里面的文件,例如:
C:/home/hello/m1.py
C:/home/hello/m2.py
m1.py中有:
- def print_m1():
- print('m1')
m2.py中有:
- def print_m2():
- print('m2')
只需要调用hello这个包就可以使用m1,m2中的函数:
- import sys
- sys.path.append('C:/home/hello')
- import m1
- import m2
- m1.print_m1()
- m2.print_m2()