您的位置:首页 > 编程语言 > Python开发

Python学习-3.Python的模块加载

2014-09-26 21:34 274 查看
Python中使用import关键字进行模块加载。

先在Visual Studio中建立PythonModuleLoad项目作为演示。

1、同目录加载

建立SameFolder.py文件

写入代码:

def printSameFolder():
print("this method is in the same folder")


修改启动文件,默认为PythonModuleLoad.py

import SameFolder
SameFolder.printSameFolder()


注意,在编写到import之后,SameFolder已经被Visual Studio只能感知到了,PTVS(Python Tools for Visual Studio)的功能还是很不错的。

2、子目录加载

建立OtherFolder文件夹,并添加OtherFolder.py

写入代码:

def printOtherFolder():
print("this method is in the other folder")


修改启动文件

import OtherFolder.OtherFolder
OtherFolder.OtherFolder.printOtherFolder()


这里解释一下,第一行import的第一个OtherFolder是指OtherFolder这个文件夹,然后第二个是指OtherFolder.py这个文件。第二行同理,即调用了OtherFolder文件夹里的OtherFolder.py里的printOtherFolder这个函数。

在这里,Visual Studio的智能提示就不行了。

3、追加目录加载

修改启动文件

import sys
sys.path.append("./OtherFolder/")

import OtherFolder
OtherFolder.printOtherFolder()


先引入sys这个Python的系统包,然后调用sys.path.append方法,添加OtherFolder这个目录路径,然后与同目录一样,加载模块就行了,这次PTVS的语法提示也正常的工作了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: