Python程序设计入门(4)模块和包

319次阅读  |  发布于5年以前

Python语言功能非常强大,除了类之外,还有模块和包的概念,这有点像perl,此处简单说说包和模块。

一、Python中的模块

模块――其实就是我们说的库(lib)的概念,不过它不仅只是可以包含一系列函数,也可以包含类,python里是没有像C语言之类,直接include某文件的,包正是这种类似的东西。

Python 引入模块的方法有两种:

1、import 模块名(实际是对应的就是 文件名.py )

2、模块名 = import("模块文件名(不带扩展名)")

也可以" import 模块名 as 别名 "这样用

例如:

复制代码 代码如下:

test.py

-- coding: gb18030 --

引入模块

import test_mod

调用模块里的函数

test_mod.my_func()

调用模块里的类

tc = test_mod.test_cls()
tc.test_func()

test_mod.py源码如下:

-- coding: gb18030 --

def my_func():
print 'I am a function in the module! '

class test_cls:
def test_func(self):
print 'I am a mothod in the class! '

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8